Python, how to create an empty file
By Flavio Copes
Learn how to create an empty file in Python using the open() function with append or write mode, why you must close it, and how to catch the OSError raised.
To create an empty file in Python, open it with the open() global function and close it right away. Opening a file that doesn’t exist creates it on disk.
open() accepts 2 parameters: the file path, and the mode.
You can use a as the mode, to tell Python to open the file in append mode:
file = '/Users/flavio/test.txt'
open(file, 'a').close()
#or
open(file, mode='a').close()
Why append mode? Because it’s the safe choice. If the file already exists, its content is not modified. The file is only created when it’s missing.
To clear the content of an existing file instead, use the w (write) mode:
open(file, 'w').close()
#or
open(file, mode='w').close()
Be careful with w. It truncates the file to zero bytes as soon as you open it. Run it on a file with data you care about, and that data is gone. That’s the pitfall to avoid here, and it’s why I default to a for this task.
Why close the file?
When you open a file, you must remember to close it after you’ve finished working with it. In this case, we close it immediately, as our goal is only to create the file.
If you don’t, the file stays open until the program ends, holding a file descriptor for no reason.
Alternatively, you can use with, which closes the file automatically:
with open(file, mode='a'): pass
What if the file must not exist yet?
There’s a third mode worth knowing: x, for exclusive creation. It creates the file, but raises an error if the file is already there:
open(file, 'x').close()
If /Users/flavio/test.txt already exists, this raises FileExistsError. Use it when overwriting or silently reusing an existing file would be a bug in your program.
Handling errors
Creating a file can raise an OSError exception, for example if the disk is full or the folder doesn’t exist. We use a try block to catch it and gracefully handle the problem by printing an error message:
file = '/Users/flavio/test.txt'
try:
open(file, 'a').close()
except OSError:
print('Failed creating the file')
else:
print('File created')
FileExistsError is a subclass of OSError, so this same block also catches the exclusive creation failure if you use the x mode.
Related posts about python: