How to Create a File in Python

When I first started working with Python over a decade ago, one of the first tasks I needed to master was how to create a file in Python. Whether you’re saving logs, generating reports, or storing user data, file creation is a fundamental part of programming.

In this tutorial, I’ll walk you through different ways to create a new file in Python, step by step. I’ll also share some practical insights from my experience that can help you avoid common mistakes and write cleaner, more efficient code.

Each method I’ll explain is simple, beginner-friendly, and something I’ve personally used in real-world projects.

Method 1 – Create a Python File Using the open() Function

The simplest and most common way to create a file in Python is by using the built-in open() function. This method gives you full control over how the file is opened, whether you want to write, read, or append data.

Here’s the basic syntax:

file = open("example.txt", "w")
file.write("Hello, this is my first file created using Python!")
file.close()
print("File created successfully!")

You can refer to the screenshot below to see the output.

python create file

In the above code, I used the “w” mode, which stands for write mode. If the file doesn’t exist, Python automatically creates it. If it already exists, it will be overwritten, so be careful.

You can also use “a” mode (append) if you want to add content without overwriting the existing file.

Here’s an example:

file = open("example.txt", "a")
file.write("\nThis line is added later using append mode.")
file.close()
print("Line appended successfully!")

You can refer to the screenshot below to see the output.

how to create a file in python

This approach is simple and works perfectly for small scripts. However, you must remember to close the file manually using file.close() to prevent memory leaks.

Method 2 – Create a File in Python Using with open()

Over the years, I’ve learned that forgetting to close files can lead to unexpected bugs, especially in larger Python applications. That’s why I always recommend using the with statement.

The with statement automatically handles file closing for you, even if an error occurs during file operations.

Here’s how it works:

with open("sales_report.txt", "w") as file:
    file.write("Monthly Sales Report - October 2025\n")
    file.write("Region: USA\n")
    file.write("Total Sales: $125,000\n")
print("Sales report created successfully!")

You can refer to the screenshot below to see the output.

create file python

In this example, I created a file named sales_report.txt and wrote multiple lines to it. Once the block of code inside with finishes executing, Python automatically closes the file.

Method 3 – Create a File Using Python’s pathlib Module

As Python evolved, new modules were introduced to make file handling more intuitive. One of my favorites is the pathlib module, available in Python 3.4 and above. pathlib provides an object-oriented approach to working with files and directories.

Here’s how you can use it to create a file:

from pathlib import Path

file_path = Path("data_output.txt")
file_path.write_text("This file was created using the pathlib module in Python.")

This single line of code creates a file (if it doesn’t exist) and writes text into it. If the file already exists, it will overwrite the existing content.

If you want to create an empty file without writing anything, you can do this:

from pathlib import Path

file_path = Path("empty_file.txt")
file_path.touch(exist_ok=True)

The touch() method works just like the Linux touch command; it creates an empty file if it doesn’t exist. The exist_ok=True parameter ensures that the code doesn’t throw an error if the file already exists.

Method 4 – Create a File Using os Module

Sometimes, I need to work with system-level operations, and that’s where the os module comes in handy. It provides tools for interacting with the operating system, including creating files and directories.

Here’s a simple example:

import os

file_name = "system_log.txt"

# Create a new empty file
with open(file_name, "w") as file:
    file.write("System log created successfully.\n")

# Verify that the file exists
if os.path.exists(file_name):
    print(f"{file_name} has been created successfully!")

You can refer to the screenshot below to see the output.

create a file in python

This method is particularly useful when you’re automating file creation in scripts that interact with your operating system, for example, creating log files or backups.

Method 5 – Create a File Using Exception Handling

In real-world Python projects, it’s always a good idea to handle exceptions gracefully. File operations can fail for many reasons, missing directories, permission issues, or invalid file names.

Here’s how I typically handle such cases:

try:
    with open("financial_data.txt", "w") as file:
        file.write("Q4 Financial Data - Confidential\n")
        file.write("Revenue: $2.5M\nExpenses: $1.8M\nNet Profit: $700K\n")
    print("File created successfully!")
except PermissionError:
    print("You do not have permission to create this file.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

This approach ensures your program doesn’t crash when something goes wrong. Instead, it prints a helpful message, making debugging much easier.

Bonus Tip – Check If a File Already Exists Before Creating It

Sometimes, you may not want to overwrite an existing file. In such cases, you can check if the file exists before creating it.

Here’s how you can do it:

import os

file_name = "customer_data.txt"

if not os.path.exists(file_name):
    with open(file_name, "w") as file:
        file.write("Customer Name, Email, Country\n")
        file.write("John Doe, john@example.com, USA\n")
    print("File created successfully!")
else:
    print("File already exists. No changes made.")

This small check can save you from accidentally deleting important data.

Here’s a practical example that I often use in my projects, creating a log file that records program events.

import datetime

def create_log_file():
    log_file = f"log_{datetime.date.today()}.txt"
    with open(log_file, "a") as file:
        file.write(f"[{datetime.datetime.now()}] Log file created successfully.\n")
    print(f"Log file '{log_file}' created and updated.")

create_log_file()

This script creates a new log file each day and appends a timestamped message. It’s a simple yet powerful way to track program activity.

Here are a few tips I’ve learned over the years for handling files effectively in Python:

  • Always use the with open() syntax, it’s cleaner and safer.
  • Use absolute paths when working with multiple directories.
  • Handle exceptions properly to avoid crashes.
  • Avoid overwriting files unless necessary.
  • Use pathlib for modern, object-oriented file management.

These practices will make your Python code more reliable and maintainable.

Creating a file in Python is one of the most basic yet essential tasks every developer should know. From the simple open() function to advanced modules like pathlib, Python gives you multiple ways to handle files efficiently.

Personally, I prefer using the with open() method for most cases because it’s clean, readable, and automatically handles closing files. But if you’re working on larger projects, combining pathlib and os can make your code even more powerful.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.