Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

How to Create a File in Python If It Doesn’t Exist

Use Python’s open() to create a missing file, choosing w to overwrite, a to append, or x to fail if it already exists.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s built-in open() in write mode to create a missing text file:

with open("example.txt", "w", encoding="utf-8") as file:
    file.write("Hello, world!n")

Mode "w" creates the file if it is missing, but it also truncates the file if it already exists. Choose a different mode if you need to preserve existing content or refuse to overwrite it.

Choose what should happen if the file already exists

Mode If the file is missing If the file exists
"w" Creates it Truncates it before writing
"a" Creates it Appends new content
"x" Creates it Raises FileExistsError
"r" Does not create it; opening a missing file raises an error Opens it for reading

These are standard open() mode behaviors described in the Python built-in open() reference.

Create or overwrite with "w"

Use "w" when replacing the file’s contents is intended. The context manager closes the file when the block ends:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
with open("example.txt", "w", encoding="utf-8") as file:
    file.write("New contentsn")

Create or append with "a"

Use "a" to preserve existing content and add data at the end. It also creates the file when it is absent:

with open("example.txt", "a", encoding="utf-8") as file:
    file.write("Another linen")

Create only if absent with "x"

Use "x" when an existing file should be treated as a collision rather than overwritten. Handle FileExistsError if that is an expected outcome for your program:

try:
    with open("example.txt", "x", encoding="utf-8") as file:
        file.write("Created only if absentn")
except FileExistsError:
    print("The file already exists")

Use pathlib for concise text writes or empty files

For a one-call text write, Path.write_text() is concise and manages opening and closing the file for you:

from pathlib import Path

Path("example.txt").write_text("Hello, world!n", encoding="utf-8")

This writes the text to the path, creating a missing file; like write mode, it replaces existing contents. For an explicit file-object workflow, use Path.open():

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from pathlib import Path

path = Path("example.txt")
with path.open("w", encoding="utf-8") as file:
    file.write("Hello, world!n")

To create an empty file, use Path.touch(). By default, exist_ok=True allows an existing path and updates its modification time. Set exist_ok=False to raise FileExistsError if it already exists:

from pathlib import Path

Path("example.txt").touch(exist_ok=False)

See the Python pathlib reference for these path methods.

Create missing parent directories first

Opening a file does not create missing directories in its path. Create the parent directories before writing:

from pathlib import Path

path = Path("output/reports/example.txt")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("Reportn", encoding="utf-8")

parents=True creates missing directory levels, while exist_ok=True avoids an error if the target directory already exists. The Python pathlib documentation describes mkdir() and its options.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Mind the path, encoding, and errors

  • Encoding: In text mode, omitting encoding uses the platform’s locale encoding. Specify encoding="utf-8" when you need consistent text encoding across machines, as documented in the open() reference.
  • Relative paths: A path such as example.txt is resolved from the process’s current working directory, which may differ from the directory containing your script.
  • Failures: Opening a file can raise OSError, for example when the path is inaccessible or permissions prevent access. Catch it when your application has a meaningful recovery action; do not assume the write succeeded.

The Python tutorial’s file I/O section also demonstrates writing files with a context manager.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.