Implement a Touch File in Python

Implement a Touch File in Python

  1. Use the pathlib.Path.touch() Function to Implement a Touch File in Python
  2. Use the os.utime() Function to Implement a Touch File in Python
  3. Use the Touch Module to Implement a Touch File in Python

Unix systems have a utility command called touch. This utility sets the access and modification times of the given file to the current time.

We will discuss how to implement the touch file in Python.

Use the pathlib.Path.touch() Function to Implement a Touch File in Python

The pathlib module allows us to create Path objects to represent different filesystem paths and work between operating systems.

We can use the pathlib.Path.touch() function to emulate the touch command. It creates a file in Python at the specified path. We specify the file mode and access flags using the mode parameter.

It also accepts an exist_ok parameter which is True by default. If this is set to False, an error is raised if the file already exists at the given path.

See the code below.

from pathlib import Path
Path('somefile.txt').touch()

Use the os.utime() Function to Implement a Touch File in Python

The os.utime() function sets the access and modification time. We can specify the time for both using the times parameter. By default, both the values are set to the current time.

We will create a function to open a file using the open() function and then use the os.time() function. The file will be opened in append mode.

For example,

import os
def touch_python(f_name, times=None):
    with open(f_name, 'a'):
        os.utime(f_name, times)
touch_python('file.txt')

Use the Touch Module to Implement a Touch File in Python

The touch module is a third-party module that can emulate the Unix touch command. We can use it to create a touch file in Python. We will use the touch.touch() function with a specified filename and path.

For example,

import touch
touch.touch('somefile.txt')

The advantage of this method over the rest is that we can also use it to create multiple files. For this, we will pass the filename and their paths as elements of a list.

See the following example.

import touch
touch.touch(['somefile.txt','somefile2.txt'])

Any file which already exists will be replaced.

Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python File

  • Get All the Files of a Directory
  • Delete a File and Directory in Python
  • Append Text to a File in Python
  • Check if a File Exists in Python
  • Find Files With a Certain Extension Only in Python
  • Read Specific Lines From a File in Python