This tutorial will go over numerous approaches for creating a file in Python when one doesn’t already exist. In this section, we’ll examine the file’s many modes and describe how they work.
If a file already exists, it will be opened; if not, a new file will be created and text added. The Python approach listed below can help us do this.
You can get more information on file handling from File Handling Methods in Python.
Create File If Not Exist in Python
We can create a file in the following ways:
- Python Create File if Not Exists Using the
open()
Method. - Python Create File if Not Exists Using the
touch()
Method.
Python Create File if Not Exists Using the open() Function
Python’s open()
method opens a file; it accepts the file path and the mode as inputs and returns the file object.
If the file does not already exist, we must provide the required file mode as an argument to the open()
function in order to create and open the file.
Syntax of open()
open(file, mode)
Arguments
file: It is the path and name of a file.
There are the following file modes available:
Mode | Description |
---|---|
w | Write mode |
r | Read mode |
a | 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 |
To truncate the file while creating a new file, use the w+
mode in the open()
function.
file = open('myfile.txt','w+')
The below code creates a file if it does not exist without truncating it using the open() function in Python.
file = open('myfile.txt','a+')
Python Create File if Not Exists Using the touch() Method
The file is created at the location specified in the path of the path.touch()
method of the pathlib module. When the exist ok parameter is set to True, the function will not take any action if the file is present.
Sample code to create a file if does not exist:
from pathlib import Path myfile = Path('myfile.txt') myfile.touch(exist_ok=True) f = open(myfile)
If the file already exists, then it won’t do anything. Otherwise, it will create a new file.