Skip to content

Python create file if not exists

  • by

Use the w+ and a+ mode in the open () function to create the file if it does not exist in Python. The a+ mode will allow us to append data to the file and w+ will truncate the file’s contents.

open(file, mode)

The open() method takes the file path and mode as input and outputs a file object.

Python creates files if not exist example

Simple example code.

file = open('data.py', 'a+')
file = open('data.json', 'w+')

Output:

Python create file if not exists

Create a 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.

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.

from pathlib import Path

fle = Path('data.py')
fle.touch(exist_ok=True)
f = open(fle)

Do comment if you have any doubts or suggestions on this Python file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading