Last modified: Feb 14, 2026 By Alexander Williams

Python Create New Text File Tutorial

Creating files is a core skill in programming. Python makes it simple. This guide shows you how.

You will learn the basic methods. We cover error handling and best practices too.

The open() Function

The open() function is your main tool. It connects your program to a file on your computer.

You give it a filename and a mode. The mode tells Python what you want to do.

To create a new file, you use the 'w' (write) mode. If the file exists, 'w' will overwrite it.

Be careful with this. Always check your filename first.


# Basic syntax to create/open a file for writing
file_object = open('my_new_file.txt', 'w')
# Remember to close the file!
file_object.close()
    

Using the 'with' Statement

Manually closing files is risky. You might forget. The with statement solves this.

It automatically closes the file for you. This is the recommended way.

It handles cleanup even if an error occurs. This prevents data corruption.


# The safe way: using 'with'
with open('data.txt', 'w') as file:
    # File is open inside this block
    # Do your writing here
    pass  # 'pass' does nothing, just a placeholder
# File is automatically closed here
    

Writing Content to Your New File

An empty file is not very useful. You need to put text inside it.

Use the write() method for this. It takes a string as an argument.

Remember, write() does not add a newline automatically. You must add '\n' yourself.


# Creating a file and writing a single line
with open('greeting.txt', 'w') as f:
    f.write('Hello, World!')

# Creating a file and writing multiple lines
with open('log.txt', 'w') as f:
    f.write('Log Entry 1\n')
    f.write('Log Entry 2\n')
    f.write('Log Entry 3\n')
    

You can also use the writelines() method. It takes a list of strings.


# Using writelines() with a list
lines_to_write = ['First line.\n', 'Second line.\n', 'Third line.\n']
with open('story.txt', 'w') as f:
    f.writelines(lines_to_write)
    

Other Useful File Modes

'w' is not the only mode. Python offers others for different tasks.

'a' (append mode) is very important. It adds text to the end of an existing file.

It will not erase the old content. Use this for logs or data collection.

'x' (exclusive creation mode) will only create a new file.

It fails if the file already exists. This prevents accidental overwrites.


# Append mode: adds to the file
with open('diary.txt', 'a') as f:
    f.write('New diary entry.\n')

# Exclusive mode: creates only if it doesn't exist
try:
    with open('unique_config.txt', 'x') as f:
        f.write('Settings go here.')
except FileExistsError:
    print("File already exists! Use a different name.")
    

Checking and Handling Errors

File operations can fail. The path might be wrong. You may lack permission.

Always use try-except blocks. This makes your program robust.

Common errors are FileNotFoundError and PermissionError.


# Safe file creation with error handling
filename = 'important.txt'
try:
    with open(filename, 'w') as file:
        file.write('All good.')
    print(f"Successfully created {filename}")
except IOError as e:
    print(f"Could not create file: {e}")
    

Practical Example: A Simple Data Logger

Let's combine everything. We'll build a small program.

It logs user input with a timestamp to a file. This is a common real-world task.


import datetime

def log_activity(message, logfile="activity_log.txt"):
    """Appends a timestamped message to a log file."""
    # Get current time
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"[{timestamp}] {message}\n"

    # Use append mode to preserve old logs
    try:
        with open(logfile, 'a') as f:
            f.write(log_entry)
        print("Log entry saved.")
    except Exception as e:
        print(f"Failed to log: {e}")

# Example usage
log_activity("Program started.")
log_activity("User performed an action.")
    

# Expected content in 'activity_log.txt'
[2023-10-27 14:30:01] Program started.
[2023-10-27 14:30:05] User performed an action.
    

Best Practices and Tips

Follow these rules for clean and safe file handling.

Always use the with statement. It's the number one rule.

Use descriptive filenames. Avoid spaces and special characters.

Specify the file encoding for portability. Use open('file.txt', 'w', encoding='utf-8').

Keep file paths relative to your script. This makes your code easier to move.

For more advanced control over text data streams, learn about the Python TextIOWrapper.

Conclusion

Creating a text file in Python is straightforward. The key function is open() with mode 'w'.

Remember to use the with statement. It manages resources for you.

Choose the right mode: 'w' to write new, 'a' to append, 'x' for safe creation.

Add error handling to make your programs reliable. This skill is a foundation for many projects.

From saving settings to logging data, file creation is essential. Once you master text files, you can explore related areas like Python text extraction from images.

Now, go ahead and start creating your own files with Python.