Path.touch - Create a file in Python

Path class has touch method that creates a file. Path is in pathlib module and useful to handle files and directories in Python.

from pathlib import Path

p = Path(__file__).parent / 'data' / 'mail.txt'

p.touch()

touch creates a file if the path doesn't exist. If the path already exists, Python do nothing. In that case, the file is not overwritten to empty content by touch. touch doesn't change the file content.

If you want to create a file or overwrite, use write_text. This method overwrites or creates if the file doesn't exist.

More: Delete a file

Python File

Python Tutorial