To create an empty file in Python, you can open a file in write mode and then use the pass keyword to not write anything to the file.

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

If you want to create empty files with different file types, then the method will be different.

A shorter solution to above is to close the file directly after opening it.

open('example.txt','w').close()

When working with files, the ability to create, delete or change existing files easily can be useful.

One such example is if you want to create an empty file.

To create an empty file in Python, you can open a file in write mode and then use the pass keyword to not write anything to the file.

Below shows you a simple example of how to create an empty text file using Python.

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

A shorter solution to above is to close the file directly after opening it. This ensures that the file is closed after creation.

open('example.txt','w').close()

Hopefully this article has been useful for you to learn how to create an empty file with Python.

Categorized in:

Python,

Last Update: March 12, 2024