How to Create File If Not Exists in Python
There are many ways you can use to create a file if it does not exist. The most common way is to use the open() function and pass the different modes as per your requirement. Other ways are using the pathlib module or use the os module and check the file’s existing condition. In this tutorial, we will use the open() method approach and the pathlib module’s approach.
Python create file if not exists.
To create a file if not exists in Python, use the open() function. The open() is a built-in Python function that opens the file and returns it as a file object. The open() takes the file path and the mode as input and returns the file object as output.
Syntax of open()
file: It is the path and name of a file.
mode: The open() function takes one of the following modes.
- w: It is for write mode.
- r: It is for reading mode.
- a: It is for append mode.
- w+: Create the file if it does not exist and then open it in write mode.
- r+: Open the file in the read and write mode.
- a+: Create the file if it does not exist and then open it in append mode.
These are the various modes you can use while creating a new file.
If you pass a+, add the text to the file or create it first if it does not exist.
The w+ mode will truncate the file and then open it in write mode, so if we do not want the file to be truncated, we should use the a+ mode.
file = open('data.py','a+')
If you run the above code, it will create a file called data.py. The file did not exist previously, but after we run the code, it has created. If the file exists and already has content, then a+ won’t remove the content.
To truncate the file while creating a new file, use the w+ mode in the open() function.
We are writing some code inside the data.py file, and then we run the app.py file with w+ mode.
file = open('data.py','w+')
Now, if you run the above code, it will truncate the file.
The w truncates existing file. docs: Modes ‘r+’, ‘w+’ and ‘a+’ open the file for updating.
One thing to note that a+ creates a file if it does not exist and, crucially, seeks the file to the end. So if you do a read immediately after opening this way, you will get nothing.
Create File if it does not exist using the touch()
There is one more way to create a file if it does not exist using the touch() method of the pathlib module. The path.touch() method creates the file at the specified path.
from pathlib import Path fle = Path('data.py') fle.touch(exist_ok=True) f = open(fle)
If the file already exists, then it won’t do anything. Otherwise, it will create a new file.
That is it for this tutorial.