Skip to content

Python create file in directory

  • by

Use the Python built-in function open() to create a file in directory. os.mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raise FileExistsError if the directory to be created already exists.

os.mkdir(path, mode = 0o777, *, dir_fd = None)

Python creates a file in a directory example

Simple example code to create file in given directory, It will create directory also if given directory not exits.

import os

path = os.getcwd()

while not os.path.exists(path + "\\testfolder"):
os.mkdir(path + "\\testfolder")

test_folder_path = path + "\\testfolder\\"
test_file = open(test_folder_path + "zero.txt", "w")


Python create file in directory

Another example

import os

path = chap_name

if not os.path.exists(path):

filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:

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