Use the open() global function to create an empty file in Python. This is the easiest way to simply create a file without truncating it in case it exists is this:
open(filename, 'mode').close() #OR f = open(path_of_the_file, mode)
List of access modes for creating an empty file.
- Write Only (‘w’): Open the file for writing. For an existing file, the data is truncated and over-written.
- Write and Read (‘w+’): Open the file for reading and writing. For an existing file, data is truncated and over-written.
- Append Only (‘a’): Open the file for writing. The data being written will be inserted at the end, after the existing data.
- Append and Read (‘a+’): Open the file for reading and writing. The data being written will be inserted at the end, after the existing data.
Python creates an empty file example
Simple example code.
Creating an empty CSV file
There are various ways to create a blank CSV file in Python. The open operator is the simplest approach to creating an empty CSV file.
with open('sample.csv', 'w') as creating_new_csv_file:
Creating an empty Text file
The extension used for text files is .txt
with open('writing.txt', 'w') as file:
Creating an empty Excel file
There are several extensions used for excel files such as xlsx for Excel Workbook, .xls for Excel 97- Excel 2003 Workbook, and Microsoft Excel 5.0/95 Workbook, .xml for XML Data and XML Spreadsheet, etc.
from openpyxl import Workbook
# create a workbook as .xlsx file
workbook = Workbook()
if __name__ == "__main__":
Do comment if you have any doubts or suggestions on this Pytohn file topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.