
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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', then it creates a new file if it doesn't exist.
Example
Following is an example, which shows how to create an empty file using the write mode 'w' -
with open('empty_file.txt', 'w') as f: pass print("File created.")
When we execute the above program, an empty text file will be created with the file name empty_file.txt and print the below message -
File created.
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 does not erase the contents if the file already exists.
Example
Following is an example, which shows how to create an empty file using the append mode 'a' -
with open('empty_file.txt', 'a') as f: pass print("File created.")
When we execute the above program, an empty text file will be created with the file name empty_file.txt if it does not already exist and prints the below message -
File created.
Using pathlib.Path.touch()
The pathlib module provides an object-oriented approach to handle file system paths. The touch() method of the Path class is used to create an empty file. It creates the file if it does not exist and does nothing if the file already exists.
Example
Following is an example, which shows how to create an empty file using pathlib.Path.touch() -
from pathlib import Path Path('empty_file.txt').touch() print("File created.")
When we execute the above program, an empty text file will be created with the file name empty_file.txt if it does not already exist, and prints the following message -
File created.
Finally, we can conclude, each method has its own advantages depending on the context in which we use them -
- We can use open('filename', 'w') when we want to create a fresh file every time.
- We can use open('filename', 'a') when we want to preserve existing content.
- We can use Path.touch() for a clean and modern approach, especially when working with file paths in a more structured way.
Note: When we can use the file extension after the file name to create empty files within different file types, such as .pdf, .csv, etc.