How to create an empty file using Python?

Creating an empty file is a common task in programming when we are initializing log files, setting up placeholders or working with automation scripts. Python provides several easy and flexible methods to create empty files. In this article, we'll go through different ways to create an empty file in Python.

Using open() with Write Mode 'w'

The open() function is the most straightforward way to create an empty file. When we use the write mode 'w', it creates a new file if it doesn't exist and overwrites the file if it already exists ?

Example

with open('empty_file.txt', 'w') as f:
    pass
print("File created using write mode.")
File created using write mode.

The pass statement does nothing, so the file remains empty. The with statement ensures the file is properly closed after creation.

Using open() with Append Mode 'a'

The open() function can also be used with append mode 'a' to create an empty file. When we use the append mode, it creates the file if it doesn't exist but preserves the contents if the file already exists ?

Example

with open('append_file.txt', 'a') as f:
    pass
print("File created using append mode.")
File created using append mode.

Using pathlib.Path.touch()

The pathlib module provides an object-oriented approach to handle file system paths. The touch() method of the Path class creates an empty file if it doesn't exist and updates the timestamp if it already exists ?

Example

from pathlib import Path

Path('pathlib_file.txt').touch()
print("File created using pathlib.Path.touch().")
File created using pathlib.Path.touch().

Creating Different File Types

You can create empty files of any type by specifying the appropriate file extension ?

from pathlib import Path

# Create different file types
Path('data.csv').touch()
Path('config.json').touch() 
Path('script.py').touch()
print("Multiple file types created.")
Multiple file types created.

Comparison

Method Overwrites Existing? Best For
open('file', 'w') Yes Creating fresh files
open('file', 'a') No Preserving existing content
Path.touch() No Modern, clean approach

Conclusion

Use open('file', 'w') to create fresh files, open('file', 'a') to preserve existing content, and Path.touch() for a modern object-oriented approach. All methods work with any file extension.

Updated on: 2026-03-24T18:34:20+05:30

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements