To implement touch in Python, you can use the pathlib module’s “Path.touch()” method. It will create any file in any specified directory.
Syntax
Path.touch(mode=0o666, exist_ok=True)
Parameters
| Name | Value |
| mode | It determines the way you want to create a file. |
| exist_ok | If the file already exists, the function succeeds if the exist_ok argument is True (and its modification time is updated to the current time). Otherwise, FileExistsError is raised. |
Importing the pathlib library
from pathlib import Path
Touch a single file
Before touching a single file
from pathlib import Path
Path("/Users/krunal/Desktop/code/pyt/database/file.txt").touch()
After touching a single file
Creating multiple files using touch
We can create multiple files by using a loop and pathlib.Path.touch() method.
from pathlib import Path
# List of files you want to touch
file_list = [
"parent/file1.txt",
"parent/app.log",
"parent/report.csv",
]
for file_path in file_list:
path = Path(file_path)
# Make sure parent directories exist
if path.parent:
path.parent.mkdir(parents=True, exist_ok=True)
# Create file if missing, or update its modification time if present
path.touch(exist_ok=True)
That is it.



