PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » File Handling » Create File in Python

Create File in Python

Updated on: December 4, 2026 | 11 Comments

In this tutorial, you’ll learn how to create a file in Python.

Python has built-in functions to work with files, so you don’t need to import any module to create one. After creating a file, you can perform other operations on it, such as writing and reading.

After reading this tutorial, you’ll learn: –

  • Create a file in the current directory or a specified directory
  • Create a file only if it doesn’t exist
  • Create a file with a date and time as its name
  • Create a file with permissions
  • Create files with pathlib, in new folders, in binary mode, and as temporary files

Table of contents

  • Create an Empty Text File
  • Create a File in a Specific Directory
  • Create a File If It Doesn’t Exist
  • Create a File With a Date and Time in Its Name
  • Create a File With Permissions
  • Create a File Using pathlib
  • Create a File in a Folder That Doesn’t Exist Yet
  • Create a Binary File
  • Create a Temporary File
  • Summary

Create an Empty Text File

We don’t have to import any module to create a new file. We can create a file using the built-in function open().

open('file_Path', 'access_mode')Code language: Python (python)

Pass the file name and access mode to the open() function to create a file. Access mode specifies the purpose of opening a file.

Below is the list of access modes for creating a file.

File ModeMeaning
wCreate a new file for writing. If the file already exists, its content is erased first.
xCreate a new file for writing (exclusive creation). If the file already exists, Python raises FileExistsError.
aOpen a file for appending. A new file is created if it doesn’t exist. Existing content is kept, and new content is added at the end.
bBinary mode. Combine it with another mode, for example, wb or xb, to create a binary file.
tText mode (the default). Combine it with another mode, for example, wt.
File access mode

Example: Create a new empty text file named ‘sales.txt’

# create an empty text file
# in the current directory
fp = open('sales.txt', 'x')
fp.close()Code language: Python (python)

Use access mode w if you want to create a file and write content to it. If the file already exists, its content is erased first.

# create a text file and write to it
with open('sales_2.txt', 'w') as fp:
    fp.write('first line')Code language: Python (python)

As you can see in the image, two new files are created in the account folder.

created files
created files

Note:

  • If you don’t specify a directory, the file is created in the current working directory, which is usually the folder you run the script from. This is called creating a file using a relative path.
  • The working directory is not always the folder that contains the script. Use os.getcwd() to check where files will be created.

You can verify the result using the following four approaches

  1. If the script executed without an error or exception
  2. By checking the working directory manually to look for a new file
  3. Use the os.listdir(directory_path) function to list all files from a folder before and after creating a file
  4. Use the os.path.isfile(file_path) function to verify if a newly created file exists in a directory.

Let’s verify our operation result.

import os

# list files from a working directory
print(os.listdir())

# verify file exist
print(os.path.isfile('sales.txt'))Code language: Python (python)

Output

['sample.txt', 'sales.txt', 'sales_2.txt']
True

Create a File in a Specific Directory

To create a file inside a specific directory, open the file using its absolute path. An absolute path contains the entire path to the file or directory.

It includes the complete directory list required to locate the file. For example, /user/Pynative/data/sales.txt is an absolute path to discover the sales.txt. All of the information needed to find the file is contained in the path string.

Let’s see the example to create a file for writing using the absolute path.

# create a text file for writing
with open(r'E:\pynative\reports\profit.txt', 'w') as fp:
    fp.write('This is first line')Code language: Python (python)

Note: With the with statement, the file is closed automatically at the end of the block, which ensures that all the resources tied up with the file are released. The r prefix makes the path a raw string, so backslashes are not treated as escape characters.

Let’s verify result using the absolute path.

import os

# list files in a directory
print(os.listdir(r'E:\pynative\reports'))
# output ['profit.txt']

# verify file exists
print(os.path.isfile(r'E:\pynative\reports\profit.txt'))
# output TrueCode language: Python (python)

Also, you can join directory path and file name to create file at the specified location.

If you have a directory path and file name in two variables, use the os.path.join() function to construct a full path. This function accepts the directory path and file name as arguments and constructs an absolute path to create a file.

Example:

import os

# Specify the directory path
path = r'E:\pynative\account'
file_name = 'revenue.txt'

# join directory and file name, then create the file
with open(os.path.join(path, file_name), 'w') as fp:
    # remove the next line if you want an empty file
    fp.write('This is a new line')Code language: Python (python)

Create a File If It Doesn’t Exist

Sometimes you must not overwrite a file that already exists. By default, opening a file in write mode (w) erases its content if it exists, and creates a new file otherwise.

We can create a file only if it is not present using the following two ways:

  • Use os.path.exists("file_path") function to check if a file exists.
  • Use the access mode x in the open() function and  exception handling.

Example 1: create file if not exists.

import os

file_path = r'E:\pynative\account\profit.txt'
if os.path.exists(file_path):
    print('file already exists')
else:
    # create a file
    with open(file_path, 'w') as fp:
        # remove the next line if you want an empty file
        fp.write('This is first line')Code language: Python (python)

Example 2: Use file access mode x

The access mode x opens a file for exclusive creation. If the file already exists, the operation fails with a FileExistsError. Use a try-except block to handle this error.

file_path = r'E:\pynative\account\profit.txt'

try:
    # create the file only if it doesn't exist
    with open(file_path, 'x') as fp:
        fp.write('This is first line')
    print('File created')
except FileExistsError:
    print('File already exists')Code language: Python (python)

This approach is safer than checking with os.path.exists() first. The check and the creation happen in one step, so another program can’t create the same file in between.

Create a File With a Date and Time in Its Name

Let’s see how to create a text file with the current date as its name. Use the datetime module to get the current date and time and assign it to the file name to create a file with the date and time in its name.

  • The datetime module has classes to access and manipulate date and time values.
  • First, get the current date and time with datetime.now().
  • Next, format it as a string with strftime() so that you can use it as a file name.
  • Finally, pass the name to the open() function to create the file.

Example

import os
from datetime import datetime

# get current date and time
x = datetime.now()

# create a file with date as a name day-month-year
file_name = x.strftime('%d-%m-%Y.txt')
with open(file_name, 'w') as fp:
    print('created', file_name)

# with name as day-month-year-hours-minutes-seconds
file_name_2 = x.strftime('%d-%m-%Y-%H-%M-%S.txt')
with open(file_name_2, 'w') as fp:
    print('created', file_name_2)

# at specified directory
file_name_3 = os.path.join(r'E:\demos\files_demos\account', x.strftime('%d-%m-%Y-%H-%M-%S.txt'))
with open(file_name_3, 'w') as fp:
    print('created', file_name_3)Code language: Python (python)

Output:

created 29-06-2021.txt
created 29-06-2021-14-57-24.txt
created E:\demos\files_demos\account\29-06-2021-14-57-24.txt

Note: Don’t use : in file names, for example, from the %H:%M:%S format. Windows doesn’t allow colons in file names, so we use hyphens instead.

Create a File With Permissions

Let’s see how to create a file with permissions that allow other users to write to it.

  • The mode argument of os.open() sets the file’s permissions when it is created. However, the operating system’s umask (usually 0o022) removes the write permission for the group and others.
  • To get the exact permissions you want, call os.chmod() after creating the file.
  • Pass the file descriptor returned by os.open() to the built-in open() function to get a normal file object.
import os

file_path = r'E:\pynative\account\sample.txt'

# create the file with read and write permission for everyone (0o666)
fd = os.open(file_path, os.O_CREAT | os.O_WRONLY, 0o666)
with open(fd, 'w') as fh:
    fh.write('content')

# the umask may have removed some permissions, so set them explicitly
os.chmod(file_path, 0o666)Code language: Python (python)

Note: Permission bits such as 0o666 apply mainly to Linux and macOS. On Windows, Python can only make a file read-only or writable. Avoid calling os.umask(0) just to create one file: it changes the permissions of every file your program creates afterward.

Create a File Using pathlib

The pathlib module offers an object-oriented way to create files. Path.touch() creates an empty file, just like the Unix touch command. If the file already exists, it only updates its modification time, unless you pass exist_ok=False, which raises FileExistsError instead. Path.write_text() creates the file and writes text to it in one call.

from pathlib import Path

# create an empty file
Path('notes.txt').touch()

# create a file and write text to it
Path('report.txt').write_text('Monthly report\n')

print(Path('notes.txt').exists(), Path('report.txt').read_text())Code language: Python (python)

Output:

True Monthly report

Create a File in a Folder That Doesn’t Exist Yet

open() creates the file but not the folders in its path. If a folder is missing, you get FileNotFoundError: [Errno 2] No such file or directory. Create the folders first with os.makedirs() or Path.mkdir(parents=True). Passing exist_ok=True avoids an error when the folders already exist.

from pathlib import Path

file_path = Path('reports') / '2026' / 'december' / 'sales.txt'

# create all missing parent folders
file_path.parent.mkdir(parents=True, exist_ok=True)

file_path.write_text('Sales report')
print('Created', file_path)Code language: Python (python)

Output (on Windows):

Created reports\2026\december\sales.txt

With the os module, the equivalent is os.makedirs(os.path.dirname(path), exist_ok=True).

Create a Binary File

To create a file that stores raw bytes, such as an image or other non-text data, add b to the access mode (wb or xb) and write a bytes object.

with open('data.bin', 'wb') as fp:
    fp.write(bytes([0, 1, 2, 255]))

with open('data.bin', 'rb') as fp:
    print(fp.read())Code language: Python (python)

Output:

b'\x00\x01\x02\xff'

Create a Temporary File

When you need a file only while your program runs, use the tempfile module. It creates a file with a unique name in the system’s temporary folder, and TemporaryFile() deletes it automatically when it is closed.

import tempfile

with tempfile.TemporaryFile('w+') as tmp:
    tmp.write('temporary data')
    tmp.seek(0)
    print(tmp.read())
# the file is deleted hereCode language: Python (python)

Output:

temporary data

Summary

TaskCode
Create an empty file (overwrite if it exists)open('file.txt', 'w').close()
Create a file and write to itwith open('file.txt', 'w') as fp: fp.write('text')
Create only if it doesn’t existopen('file.txt', 'x') (raises FileExistsError)
Create an empty file with pathlibPath('file.txt').touch()
Create missing folders firstPath('a/b').mkdir(parents=True, exist_ok=True)
Create a binary fileopen('file.bin', 'wb')
Create a temporary filetempfile.TemporaryFile()
Ways to create a file in Python

Filed Under: Python, Python File Handling

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python File Handling

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python File Handling
TweetF  sharein  shareP  Pin

  Python File Handling

  • File Handling In Python
  • Create File in Python
  • Open a File in Python
  • Read File in Python
  • Write to File in Python
  • Python File Seek
  • Rename Files in Python
  • Delete Files in Python
  • Copy Files in Python
  • Move Files in Python
  • List Files in a Directory
  • File Handling Quiz

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com