To touch a file using Python, the easiest way is with the Path.touch() function from the pathlib module. Touching a file means creating a new file or updating a timestamp of an existing file.

from pathlib import Path


When working with files and directories in Python, the ability to easily add, modify or remove files is very valuable. ‘

One such operation is touching a file. Touching a file can update the timestamp of the file in a directory or create a new file.

With the Python pathlib module, we can perform many operations to access files and directories in our environments.

The Path class of the pathlib module has a function called touch(). With Path.touch() you can touch files in your Python code.

Below is an example of how to touch a file in your working directory in Python.

from pathlib import Path


You can touch a file by passing any valid path to Path.

from pathlib import Path


Updating the Timestamp of a File by Touching the File in Python

Touching an existing file will update the timestamp of that file. Touching an existing file will not modify any of the contents of that file.

To update the timestamp of an existing file, just pass the path of that file to Path and use the touch() function.

from pathlib import Path

with open('new_file.txt', 'w') as f:
    f.write('This is a file with some content.')

#Other steps taking time...

#Update the timestamp to now

Using the touch Module to Touch Files in Python

You can also use the Python touch module to touch files in Python.

The touch() function in the touch module allows us to touch one or more files in a single call.

Below is an example of how to use the touch module touch() function in Python.

import touch

touch.touch(["", ""])

Hopefully this article has been useful for you to learn how to touch files in Python.

Categorized in:


Last Update: February 26, 2024