Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

How to Create File If It Does Not Exist in Python

  • 23 Apr, 2025
  • Com 0
How to Create a File If Exists in Python

Here are three ways to create a file if it does not exist in Python:

  1. Using with open() method with “x” mode
  2. Using pathlib.Path.touch()
  3. 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:

newdir empty directory

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)

Created a new file

If you open the filename.txt file, it looks like this:

Content of the file

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:

Before creating a file using open() function

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:

Creating an empty file using pathlib module's Path() function

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:

Before creating a file

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")

 

Use the os.path.exists() function in combination with open() function.

That’s it!

Post Views: 23
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to Read Text File into List in Python
How to Implement Touch using Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend