The Wayback Machine - https://web.archive.org/web/20240604083722/https://www.geeksforgeeks.org/create-an-empty-file-using-python/
Open In App

Create an empty file using Python

Last Updated : 12 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

File handling is a very important concept for any programmer. It can be used for creating, deleting, and moving files, or to store application data, user configurations, videos, images, etc. Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. In this article, we will see how to create a Python file.

Pre-Requisite

Refer to the following articles to check the basics of file handling.

Creating an empty file in Python

File handling can also be used for creating a file. Even files with different extensions like .pdf, .txt, .jpeg can be created using file handling in Python. To create a file, the file must be open for writing. To open a file for writing access mode of file must be w, a, w+, a+. Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. Below is the list of access modes to create a file in Python:

  • 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.

Example 1: Creating a File Using Python’s OS Module

In this example, we are using OS Module to create a Python file. we will create a new file myfile.txt. To verify this we will use os.listdir() method of os module to list out the directories before and after creating a new file.

Python3




# importing module
import os
 
# path of the current script
path = 'D:/Pycharm projects/gfg'
 
# Before creating
dir_list = os.listdir(path)
print("List of directories and files before creation:")
print(dir_list)
print()
 
# Creates a new file
with open('myfile.txt', 'w') as fp:
    pass
 
# After creating
dir_list = os.listdir(path)
print("List of directories and files after creation:")
print(dir_list)


Output:

List of directories and files before creation:
['.idea', 'gfg.py', 'venv']
List of directories and files after creation:
['.idea', 'gfg.py', 'myfile.txt', 'venv']

Example 2: Creating a New File at a Specified Location

To create a file in Python at a specified location os module is used. In this example, the Python script uses the os module to create an empty file named ‘myfile.txt’ in the specified path ‘D:/Pycharm projects/GeeksforGeeks/Nikhil’. The script first displays the list of directories and files before and after the file creation.

Python3




import os
 
# Specify the path
path = 'D:/Pycharm projects/GeeksforGeeks/Nikhil'
 
# Specify the file name
file = 'myfile.txt'
 
# Before creating
dir_list = os.listdir(path)
print("List of directories and files before creation:")
print(dir_list)
print()
 
# Creating a file at specified location
with open(os.path.join(path, file), 'w') as fp:
    pass
    
# After creating
dir_list = os.listdir(path)
print("List of directories and files after creation:")
print(dir_list)


Output:

List of directories and files before creation:
['test_nikhil.txt']
List of directories and files after creation:
['myfile.txt', 'test_nikhil.txt']


Similar Reads

Python | Create an empty text file with current date as its name
In this article, we will learn how to create a text file names as the current date in it. For this, we can use now() method of datetime module. The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute
1 min read
Create a GUI to convert CSV file into excel file using Python
Prerequisites: Python GUI – tkinter, Read csv using pandas CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma. Modules Needed Pandas: Python i
3 min read
How to create a duplicate file of an existing file using Python?
In this article, we will discuss how to create a duplicate of the existing file in Python. Below are the source and destination folders, before creating the duplicate file in the destination folder. After a duplicate file has been created in the destination folder, it looks like the image below. For automating of copying and removal of files in Pyt
5 min read
Check If a Text File Empty in Python
Before performing any operations on your required file, you may need to check whether a file is empty or has any data inside it. An empty file is one that contains no data and has a size of zero bytes. In this article, we will look at how to check whether a text file is empty using Python. Check if a Text File is Empty in PythonBelow are some ways
4 min read
How to Find the First Empty Row of an Excel File in Python
When working with data in Excel files, one common task is to find the first empty row where new data can be added. Whether you're automating a data entry process or performing data analysis, Python offers several methods to accomplish this task efficiently. In this article, we'll explore different approaches to finding the first empty row of an Exc
2 min read
How to check if a csv file is empty in pandas
Reading CSV (Comma-Separated Values) files is a common step in working with data, but what if the CSV file is empty? Python script errors and unusual behavior can result from trying to read an empty file. In this article, we'll look at methods for determining whether a CSV file is empty before attempting to read it. This will help you deal with the
4 min read
How to create an empty class in Python?
A class is a user-defined blueprint or prototype from which objects are created. Class can be considered as a user-defined data type. Generally, a class contains data members known as attributes of the class and member functions that are used to modify the attributes of the class. But have you ever wondered how to define an empty class i.e a class
2 min read
How to Create an Empty Figure with Matplotlib in Python?
Creating a figure explicitly is an object-oriented style of interfacing with matplotlib. The figure is a basic building block of creating a plot as Matplotlib graphs our data on figures. This figure keeps track of all other components such as child axes, legends, title, axis, etc. Steps to create an empty figure : First, we import the matplotlib li
2 min read
How to create an empty matrix with NumPy in Python ?
The term empty matrix has no rows and no columns. A matrix that contains missing values has at least one row and column, as does a matrix that contains zeros. Numerical Python (NumPy) provides an abundance of useful features and functions for operations on numeric arrays and matrices in Python. If you want to create an empty matrix with the help of
3 min read
Python | Create a stopwatch using clock object in kivy using .kv file
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Kivy Tutorial - Learn Kivy with Examples. Clock Object: The Clock object allows you to schedule a function call in
6 min read
Article Tags :
Practice Tags :