How to create an empty file using Python?

PythonServer Side ProgrammingProgramming

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")
raja
Published on 27-Dec-2017 11:28:55
Advertisements