To create an empty file in Python, use the “with open()” statement with write mode (‘w’) and add the pass statement, which ensures no content is written.
file_name = "empty_file.txt" with open(file_name, 'w') as f: pass # Ensure no content is written print(f"File '{file_name}' created successfully (or overwritten).") # Output: File 'empty_file.txt' created successfully (or overwritten).
This approach is ideal for creating a new file or resetting an existing one to an empty state.
However, if an existing file with the content already exists, it will override the new file, potentially causing data loss, which is the main con of this approach.
What if the file already exists?
If the file already exists and you don’t want to override, use the with open() statement with ‘x’ (exclusive creation ) mode because it throws FileExistsError and prevents accidental overrides.
file_name = "empty_file.txt" try: with open(file_name, 'x') as file: pass except FileExistsError: print("File already exists!") # Output: File already exists!
We used the try/except mechanism to handle the FileExistsError, but this way, it won’t create an overriding file.
Creating multiple empty files
To create multiple empty files, we can use the modern approach (Python 3.4+) using the pathlib module. It provides the Path.touch() method, which helps us create a file. Using a for loop, we can create multiple files.
The Path.touch() method creates an empty file or updates the timestamp of an existing one without modifying its content.
from pathlib import Path for i in range(3): Path(f'output/empty_file_{i}.txt').touch() print("Empty files created in 'output' directory.") # Output: Empty files created in 'output' directory.
Here is the folder before creating multiple files:
After running the above program, we have 3 empty files like this:
Use pathlib.Path.touch() for simplicity and cross-platform compatibility.
Creating an empty file in a non-existent directory
If you attempt to create a file in a directory that doesn’t exist, it raises FileNotFoundError.
To handle that error, use os.makedirs() method, which will create a non-existent directory.
import os from pathlib import Path # Create directory if it doesn't exist os.makedirs('new_folder', exist_ok=True) Path('new_folder/empty_file.txt').touch()
Why do we need to create a blank file?
- We can reserve a filename for future use. For example, log files or data config files.
- It creates files for testing file operations.
- There are some applications that require an empty file to exist before processing.