How to create an empty csv file in Python?
Python offers several ways to create an empty csv file. The easiest way to create an empty csv file is the with open operator. It is available without the need to import any additional modules. However it is also possible to create csv files with Python modules such as pandas. In this how to, multiple ways are shown to create an empty csv file, choose the one you prefer.
create an empty csv file using with open
To create an empty csv file using with open, pass in the name of the new file and 'w' as second argument to make the file writable.
If the file name is non-existing a new csv file is created.
If the file exists, the content will be replaced. To prevent this from happening pass in 'a' to append the content to the file.
# create empty csv file using with open
with open('new.csv', 'w') as my_new_csv_file:
It is recommended to check if the file already exists or use 'a' instead of 'w' to append to the file if it does exist.
If the 'w' parameter is used for the access mode argument, the content in the file will be replaced by the new content.
Use 'a' instead of 'w' to append instead of overwriting.
# create empty csv file using with open - 'a' appends content if file exists
with open('new.csv', 'a') as my_new_csv_file:
Python doesn't offer a built-in function to check if a file already exists, use the os.stat() method to check if the file contains content before overwriting it.
create an empty csv file using pandas
In Python some modules have methods to create files and open files. One of them is the pandas module.
To create an empty csv file with pandas, use the .to_csv() method.
# create empty csv file using pandas
import pandas as pd
# create new pandas DataFrame
df = pd.DataFrame(list())
# write empty DataFrame to new csv file
In this example, the pandas module is important. Then an empty DataFrame is created based on an empty list. Finally the empty DataFrame is written using the .to_csv() method. Since the file doesn't exist, it is created.
verify that file is empty
It is recommended to check if a file is really empty, before writing to it. If this check is not done, some important data can be overwritten.
Another way to prevent data loss by overwriting is to use the 'a' argument for with open() to append the new content to a file.
To check if the file is empty, use the .stat() method of the os module.
# check if file is empty
os.stat('new.csv').st_size == 0
If the file is empty, True is returned. If the file is not empty, False is returned.
If the file doesn't exist, a FileNotFoundError exception is raised.
FileNotFoundError: [Errno 2] No such file or directory: 'new.csv'