Table of Contents

What Will You Learn
In this tutorial, you'll explore Python's file handling capabilities, focusing on creating new text files. You'll learn how to use the open() function with different modes ('w', 'x', 'a') to create files, understand the behavior when files already exist, and manage file resources efficiently using the with statement. The guide also covers best practices for handling file creation errors and ensuring that files are created in the correct directories, equipping you with the skills to manage file creation effectively in Python.


Creating a new text file is one of the first file-handling skills every Python programmer must learn. Whether you're logging events, generating reports, or saving output, being able to create and manage text files allows your applications to store data for later use. It also enables communication between programs, users, and systems through file-based interactions.

By mastering file creation, you gain control over data persistence and automation. It’s also an essential step toward working with more advanced concepts like file I/O, data serialization, and configuration management.

Fortunately, Python makes file creation easy and readable using built-in functions like open().

How to Create a New Text File in Python?

To create a new text file in Python, use the open() function with mode "w" (write) or "x" (exclusive creation). The "w" mode will create the file if it doesn’t exist, or overwrite it if it does. The "x" mode will create the file only if it does not already exist and raise an error otherwise. After opening the file, use .write() to add content. Always use the with statement to ensure the file is properly closed.


    # Create a new file (overwrite if exists)
    with open("new_file.txt", "w") as f:
        f.write("This is a new file.")

    # Create a new file (only if it doesn't exist)
    with open("unique_file.txt", "x") as f:
        f.write("This file must not already exist.")

Using the open() Function to Create a New Text File

The open() function is the most direct way to create a new text file in Python. When used with mode "w", it creates the file if it doesn't exist and overwrites it if it does. If you want to avoid overwriting existing files, use mode "x", which raises a FileExistsError if the file is already present. This gives you flexibility to either replace or preserve previous content depending on the use case. Always use the with statement to ensure safe file handling and automatic closure. You can start writing to the file immediately after opening it.


    # Example 1: Create or overwrite a file
    with open("report.txt", "w") as f:
        f.write("This report was generated by the system.")

    # Example 2: Create a file only if it doesn't exist
    try:
        with open("config.txt", "x") as f:
            f.write("default_settings=True")
    except FileExistsError:
        print("File already exists. Creation skipped.")

How to Check If a File Already Exists Before Creating?

To avoid overwriting existing data, you can check whether a file already exists before attempting to create it. Python provides two reliable methods: os.path.exists() from the os module and Path.exists() from the pathlib module. Both return True if the file exists and False otherwise. This allows you to conditionally create new files or alert the user before proceeding. It’s especially useful for configuration files, logs, or any case where preserving existing data is important. These checks help prevent accidental overwrites and increase the safety of your file operations.


    # Example 1: Using os.path.exists()
    import os

    if not os.path.exists("data.txt"):
        with open("data.txt", "w") as f:
            f.write("Initializing file.")

    # Example 2: Using pathlib.Path.exists()
    from pathlib import Path

    path = Path("session.log")
    if not path.exists():
        path.write_text("New session started.\n")

Common Beginner Mistakes When Creating Text Files in Python

Using "w" Mode Without Understanding Overwrites

One of the most common mistakes is using "w" mode to create a file without realizing it overwrites existing content. Beginners often assume it will only add new content, but "w" clears the entire file before writing. This leads to accidental data loss. To avoid this, use "a" to append or check if the file exists before using "w".


    # Wrong
    with open("log.txt", "w") as f:
        f.write("New log\n")  # Overwrites entire file

    # Correct
    with open("log.txt", "a") as f:
        f.write("New log\n")  # Adds to file

Using "x" Without Handling FileExistsError

Beginners often try to use "x" mode to create files but forget to handle the case where the file already exists. This causes a FileExistsError that crashes the program. You should always wrap "x" mode in a try/except block to handle this exception and give feedback to the user.


    # Wrong
    with open("output.txt", "x") as f:
        f.write("Test")  # Error if file exists

    # Correct
    try:
        with open("output.txt", "x") as f:
            f.write("Test")
    except FileExistsError:
        print("File already exists.")

Forgetting to Use the with Statement

A frequent beginner mistake is manually opening a file and forgetting to close it. This can leave files locked, lead to data loss, or cause errors. Always use the with statement, which automatically handles closing the file, even if an error occurs during writing.


    # Wrong
    f = open("notes.txt", "w")
    f.write("Don't forget!")
    # f.close() is missing

    # Correct
    with open("notes.txt", "w") as f:
        f.write("Don't forget!")

Not Checking If a File Exists

Some beginners try to blindly create files without checking if they already exist, which can lead to overwriting important data. This is especially risky in automation scripts. Use os.path.exists() or Path().exists() to verify file existence before writing to it.


    # Wrong
    with open("config.txt", "w") as f:
        f.write("Settings")

    # Correct
    import os
    if not os.path.exists("config.txt"):
        with open("config.txt", "w") as f:
            f.write("Settings")

Writing to Files Without String Conversion

When writing data like integers, lists, or dictionaries, beginners sometimes forget to convert the data to a string. This results in a TypeError. You must always convert data using str() or format it properly using f-strings before calling write().


    # Wrong
    age = 30
    with open("data.txt", "w") as f:
        f.write(age)  # TypeError

    # Correct
    with open("data.txt", "w") as f:
        f.write(str(age))

Frequently Asked Questions

How do I create a new text file in Python?

To create a new text file in Python, use the built-in open() function with mode "w" or "x". Mode "w" creates the file if it doesn't exist or overwrites it if it does. Mode "x" is used for exclusive creation — it creates a file only if it doesn't already exist, and raises a FileExistsError otherwise. After opening the file, you can use .write() to add content. It's best practice to use the with statement to automatically manage the file's context and avoid file locking or memory issues.


      # Create a new file and write to it
      with open("log.txt", "w") as file:
          file.write("Log started\n")
      

This approach ensures the file is safely created and closed after writing, even if an error occurs.

How can I check if a file exists before creating it?

To avoid overwriting an existing file, you can use os.path.exists() from the os module or Path.exists() from the pathlib module. Both methods return True if the file already exists and False otherwise. This allows you to conditionally create a new file only if it does not already exist. It’s a safe way to prevent data loss and build more robust scripts.


      import os
      if not os.path.exists("data.txt"):
          with open("data.txt", "w") as f:
              f.write("New file created.")
      

Using this technique is especially useful when generating reports, logs, or backups that should not be overwritten.

What is the difference between write (w) and exclusive creation (x) modes?

The difference between "w" and "x" modes lies in how they handle existing files. The "w" mode creates a new file or overwrites an existing one without warning. It's suitable for scenarios where overwriting data is expected, such as logs or regenerated outputs. On the other hand, "x" is safer when you want to prevent overwriting; it will raise a FileExistsError if the file already exists.


      # "w" mode — overwrites if file exists
      with open("report.txt", "w") as f:
          f.write("New report")

      # "x" mode — error if file exists
      with open("report.txt", "x") as f:
          f.write("Initial report")
      

Use "x" when data integrity is critical and you want to avoid accidental data loss.

Why does my script fail with FileExistsError?

The error FileExistsError occurs when you're using open() with mode "x" to create a file, and that file already exists. This mode is designed for exclusive creation and fails if the file is present. To handle this safely, you should wrap the file operation in a try/except block and notify the user or create a file with a new name.


      try:
          with open("data.txt", "x") as f:
              f.write("Fresh start")
      except FileExistsError:
          print("File already exists — choose a new name.")
      

This is the correct approach when you want to protect existing data from being overwritten.

Can I create a file in a folder that doesn’t exist yet?

No, Python will not create missing folders automatically when you try to create a file. If the directory in the path doesn’t exist, Python will raise a FileNotFoundError. To solve this, use os.makedirs() or Path.mkdir() from the pathlib module to create the full directory structure before creating the file.


      from pathlib import Path

      Path("logs/2025").mkdir(parents=True, exist_ok=True)
      with open("logs/2025/output.txt", "w") as f:
          f.write("Log started")
      

Always ensure the target directory exists to avoid unexpected errors during file creation.