In this article we will show you the solution of python create empty file, the concept of file handling is one of the most important concepts for any programmer. Among its many applications, it can create, delete, move, and store various types of data, including application data, user configurations, videos, images, etc.
File handling is also supported in Python, allowing users to read and write files and execute many operations on them.
In addition to creating files, file handling can also be used to handle them.
By using Python's file handling function, even files with different extensions can be created, such as .pdf, .txt, and .jpeg. Files must be open for writing before they can be created.
A file must be opened with one of the following access modes: w, a, w+, a+. Depending on the access mode, different operations can be performed on the opened file.
We will now discuss the idea of how to create an empty file in python with an example.
Step By Step Guide On Python Create Empty File :-
# Python program to demonstrate # creation of new file import os # Specify the path path = 'D:/Pycharm projects/TalkersCode/Amruta' # Specify the file name file = 'test.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 # To write data to new file uncomment # this fp.write("New file created") # After creating dir_list = os.listdir(path) print("List of directories and files after creation:") print(dir_list)
- Import the os module which provides a way of interacting with the os file system in python.
- Specify the path where the file should be created.
- Specify the name of the file to be created.
- Print the list of directories and files in the specified path before creating the file using the os.listdir() method.
- Open the file with open() method and use os.path.join() method to join the specified path and file name to create the full file path.
- Create an empty file by using the 'w' mode with the open() method.
- Comment out the pass keyword and uncomment the fp.write() method to write data to the new file.
- Print the list of directories and files in the specified path after creating the file using os.listdir() method.
Conclusion :-
As a result, we have successfully learned how to create an empty file in python with an example. We learned how to make an empty Python file in this post.
If you want an empty file, just use the open() function and specify the suitable mode for your needs.
I hope this article on python create empty file helps you and the steps and method mentioned above are easy to follow and implement.