Skip to content

Python create empty file

  • by

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:
pass

Creating an empty Text file

The extension used for text files is .txt

with open('writing.txt', 'w') as file:
pass

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
def create_workbook(path):
workbook = Workbook()
workbook.save(path)


if __name__ == "__main__":
create_workbook("file.xlsx")

Output:

Python create empty file

Do comment if you have any doubts or suggestions on this Pytohn file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading