Here are three ways to create a file if it does not exist in Python:
- Using with open() method with “x” mode
- Using pathlib.Path.touch()
- Using os.path.exists()
Method 1: Using with open() with “x” mode
Python’s built-in open() method supports an exclusive mode (“x”) that creates a file, but raises a FileExistsError if the file already exists. If the file already exists, we need to handle the FileExistsError, and that’s where we can use the try/except mechanism.
It will prevent the accidental overwrite, which prevents data loss.
Let’s say we want to create a new file called “filename.txt” if it does not exist inside the “newDir” directory.
Before creating a file, the “newDir” directory looks like this:
You can see in the above screenshot that the directory is empty!
Now, we will create a file:
try: with open("newDir/filename.txt", 'w') as file: file.write("Creating a successful file") except FileExistsError: print(FileExistsError)
If you open the filename.txt file, it looks like this:
Method 2: Using touch() method
The touch() method of a Path object from the pathlib module creates an empty file if it does not already exist, without opening it.
Before creating a file, our destination directory “newDir” looks like this:
The directory is empty. That means the file does not exist.
from pathlib import Path
file = Path('newDir/filename.txt')
file.touch(exist_ok=True)
f = open(file)
If you run the above code, it will create a file that looks like this:
Method 3: Using the os.path.exists() function
You can use the os.path.exists() function to check whether a path exists, and if it does not, then use the open() function to create a file.
Before creating a file, our directory looks like this:
Now, use the os.path.exists() function in combination with open() function.
import os file_path = "newDir/filename.txt" # Ensure parent directory exists os.makedirs(os.path.dirname(file_path), exist_ok=True) if not os.path.exists(file_path): with open(file_path, "w") as f: f.write("Creating a successful file\n") print(f"Created {file_path}") else: print("File Exists")
That’s it!