How to create an empty text file in Python?
Python offers multiple ways to create an empty text file. The simplest way is using with open to create a new file.
create an empty text file using with open
# create empty text file using with open
with open('new.txt', 'w') as my_new_text_file:
pass
If the file name is non-existing a new text file is created. However, if the file exists the content is replaced.
To change the access mode to appending content instead of replacing it, use 'a' for the access mode argument.
The following table shows the available access modes for creating a file.
flag |
access mode |
w |
create and write into file, truncate existing content |
x |
open a file, exclusively for creation. If file exists, the operations fails |
a |
open a file, in the append mode. New content is added at the end of the file. |
b |
open a binary file |
t |
create and open a file in text mode |
create an empty text file in append mode
To create a new empty text file in append mode use the flag a.
# create an empty text file in append mode
# open file in append access mode
fp = open('newfile.txt', 'a')
# write a line to the file
fp.write('new line')
# close file
fp.close()
The file is opened in append mode and the file pointer is used to write a line and then close the file.
The integer 8 is returned, to indicate that 8 characters have been written to the file.
8
create an empty text file using os.mknod() method
This option only works on unix-based systems, not on windows. However it is the only option that only creates the file, without opening it.
To create an empty text file use the os.mkonod() method.
# create empty text file using os.mknod()
import os
os.mknod("newfile.txt")
If the permissions to create the file are not set, an PermissionsError exception will be raised.
PermissionError: [Errno 1] Operation not permitted
Best practice is to wrap the creation of a new file into a try/except block.
create file in another directory
By default a new file is created in the working directory. To create the file in another directory the file path can be specified.
# create file in test directory
fp = open('test/newfile.txt', 'a')
# write a line to the file
fp.write('new line')
# close file
fp.close()
In this example the new file is created in the test directory. If Python doesn't have writing rights, this can be modified using the chmod() method of the os module.
verify that file exists
To verify that a file exists, for example after we've created it, use the .isfile() method of the os module.
# verify that file exists
import os
print(os.path.isfile('newfile.txt'))
If the file exists, True is returned. If the file doesn't exists, False is returned.
True