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
Path("file_name.py").touch()
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
Path("file_name.py").touch()
You can touch a file by passing any valid path to Path.
from pathlib import Path
Path("C:/Users/TheProgrammingExpert/Documents/file_name.py").touch()
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
Path("new_file.txt").touch()
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("file_name.py")
touch.touch(["file_name1.py", "file_name2.py"])
Hopefully this article has been useful for you to learn how to touch files in Python.