Last modified: Feb 06, 2026 By Alexander Williams

Python Write to File: A Complete Guide

Writing data to a file is a core skill in Python programming. It allows your programs to save information permanently. This could be user data, program logs, or generated reports.

Python makes this process simple and intuitive. This guide will walk you through everything you need to know. You will learn the essential functions and best practices.

Opening a File for Writing

Before you can write, you must open the file. You use the built-in open() function. This function returns a file object.

The key is the mode you specify. For writing text, you use the 'w' mode. This mode will create a new file. If the file already exists, it will be overwritten.

To open a file without overwriting, use 'a' mode for appending. This adds new content to the end of an existing file.


# Open a file for writing (creates or overwrites)
file_object = open('my_data.txt', 'w')

# Always close the file when done
file_object.close()
    

The write() Method

The primary tool for writing is the write() method. It takes a single string as an argument. It writes that string directly to the file.

Important: write() does not add a newline character automatically. You must include '\n' in your string if you want to move to the next line.


# Open the file
file = open('example.txt', 'w')

# Write a single string
file.write('Hello, World!')

# Write another string on a new line
file.write('\nThis is a second line.')

# Close the file to save changes
file.close()
    

After running this code, the file 'example.txt' will contain:


Hello, World!
This is a second line.
    

The writelines() Method

What if you have a list of strings to write? You could use a loop with write(). A better way is the writelines() method.

It takes a list (or any iterable) of strings. It writes each string to the file, one after the other. Like write(), it does not add newlines.


lines_to_write = ['First line\n', 'Second line\n', 'Third line\n']

file = open('lines.txt', 'w')
file.writelines(lines_to_write)
file.close()
    

The resulting file will have three separate lines because we included '\n' in each string.

Using the 'with' Statement (Recommended)

Manually opening and closing files is error-prone. If an error occurs, the file might not close properly. This can lead to data loss or corruption.

The best practice is to use the with statement. It creates a context manager. The file is automatically closed when the block of code finishes, even if an error happens.


# Using 'with' is safe and clean
with open('safe_example.txt', 'w') as file:
    file.write('This data is safe.\n')
    file.write('The file will close automatically.')
# File is closed here, outside the 'with' block
    

You should use the with statement for all file operations. It is the standard and most reliable method.

Appending to a File

Overwriting is not always what you want. Often, you need to add to existing data. This is where append mode ('a') comes in.

Opening a file in 'a' mode lets you write at the end of the file. If the file doesn't exist, Python will create it for you.


# First, create a file with some content
with open('log.txt', 'w') as log:
    log.write('Log started.\n')

# Now, append new entries
with open('log.txt', 'a') as log:
    log.write('User logged in at 10:00 AM.\n')
    log.write('Action completed at 10:05 AM.\n')
    

The 'log.txt' file will now contain all three lines, with the new data added to the end.

Writing Numbers and Other Data Types

The write() method only accepts strings. You cannot directly write an integer or a list. You must first convert the data to a string.

For this, use the str() function or formatted string literals (f-strings). F-strings are a modern and very readable way to format strings in Python.


user_score = 95
user_name = "Alice"

with open('scores.txt', 'w') as f:
    # Convert integer to string
    f.write('Score: ' + str(user_score) + '\n')

    # Use an f-string for cleaner formatting
    f.write(f'Player: {user_name} - Score: {user_score}\n')
    

Handling File Paths and Errors

Sometimes writing to a file can fail. The directory might not exist. You might not have permission. It's good practice to handle these potential errors.

You can use a try-except block to catch and manage exceptions. The most common one is FileNotFoundError for missing directories.


try:
    with open('/a/nonexistent/folder/myfile.txt', 'w') as f:
        f.write('test')
except FileNotFoundError:
    print("Error: The directory path does not exist.")
except PermissionError:
    print("Error: You don't have permission to write here.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
    

This makes your program robust and user-friendly. It won't crash unexpectedly.

Conclusion

Writing to a file in Python is straightforward. Remember to use the open() function with the correct mode: 'w' to write new content or 'a' to append.

Always prefer the with statement for safety. Use write() for single strings and writelines() for lists. Convert non-string data before writing.

Mastering these basics opens the door to building data-driven applications. You can now create logs, save user settings, and export results from your Python programs.