Table of Contents
Creating Files in Python
File handling is a handy concept in programming. We can write and read data to files. In Python, to create or open a file, we use the open()
function. It creates an object of file handling that can read or write data to files.
Ways to create file if not exists in Python
In this article, we will create a file that does not already exist in Python.
Using the open()
function
As discussed earlier, the open()
function creates a file handling object that opens or creates a file at the given path. There are several modes that we can use with this function.
The r
mode opens files in the read mode. Similarly, the w
and a
modes open the given file in write and append modes, respectively. The w
mode truncates the file’s content.
To create a file if it does not exist, we use the w+
and a+
mode. The a+
mode will allow us to append data to the file, and w+
will truncate the file’s contents.
We will now demonstrate how to use both these methods.
For example,
1 2 3 4 |
file1 = open('file.txt','a+') file2 = open('file.txt','w+') |
Using the pathlib.Path.touch()
function
The path.touch()
function can check if a file exists at a given path or not. We first set the path of the file using the Path()
constructor.
We set the parameter exist_ok
as True in the path.touch()
function, and it will do nothing if the file exists at the given path. Now, we proceed with the open()
function to create a file.
For example,
1 2 3 4 5 6 |
from pathlib import Path file1 = Path('Article\\file.txt') file1.touch(exist_ok=True) f = open(file1) |
Using the os.path.exists()
function
Similar to the previous method, we can use the os.path.exists()
function to check whether a path exists or not. If it does exist, then the function will return True, else it returns False.
For example,
1 2 3 4 5 6 7 |
import os if (os.path.exists("file.txt") == False): f = open("file", "w") else: print("File Exists") |
Using the try
and except
block
The try
and except
block can deal with exceptions in Python. If we open a file in the read mode and it does not exist, then an exception is raised. We can catch this using the try
and except
block and create the file after catching the exception.
See the code below.
1 2 3 4 5 6 7 8 9 |
p = 'file.txt' try: f = open(p,'r') print("File Exists") except IOError: f = open(p, 'w+') print("File Created") |
Further reading:
Conclusion
In all the methods we discussed, the open()
function only creates a file. We can set different modes within this function to create a file if it does not exist. Otherwise, we can use the touch()
or exists()
function to check if a path exists or not. We can also use the try
and except
block as shown.
That’s all about how to create file if not exists in Python.