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
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 Mode | Meaning |
|---|---|
w | Create a new file for writing. If the file already exists, its content is erased first. |
x | Create a new file for writing (exclusive creation). If the file already exists, Python raises FileExistsError. |
a | Open 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. |
b | Binary mode. Combine it with another mode, for example, wb or xb, to create a binary file. |
t | Text mode (the default). Combine it with another mode, for example, wt. |
Example: Create a new empty text file named ‘sales.txt’
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.
As you can see in the image, two new files are created in the account folder.

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
- If the script executed without an error or exception
- By checking the working directory manually to look for a new file
- Use the
os.listdir(directory_path)function to list all files from a folder before and after creating a file - 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.
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.
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.
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:
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.
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.
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
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 (usually0o022) 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-inopen()function to get a normal file object.
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.
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.
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.
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.
Output:
temporary data
Summary
| Task | Code |
|---|---|
| Create an empty file (overwrite if it exists) | open('file.txt', 'w').close() |
| Create a file and write to it | with open('file.txt', 'w') as fp: fp.write('text') |
| Create only if it doesn’t exist | open('file.txt', 'x') (raises FileExistsError) |
| Create an empty file with pathlib | Path('file.txt').touch() |
| Create missing folders first | Path('a/b').mkdir(parents=True, exist_ok=True) |
| Create a binary file | open('file.bin', 'wb') |
| Create a temporary file | tempfile.TemporaryFile() |
