Computer >> Computer tutorials >  >> Programming >> Python

How to create an empty file using Python?


The easiest way to simply create a file without truncating it in case it exists is −

open('my_file.txt', 'a').close()

In Python 3.4+, you can directly use the pathlib module to touch files. For example,

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

You can also create new files without opening them using the os module. The method mknod() creates a filesystem node (file, device special file or named pipe) named filename. For example,

import os
os.mknod("my_file.txt")