Last modified: Feb 19, 2026 By Alexander Williams
Python Write to File: Save Output Easily
Writing data to a file is a core skill in Python programming.
It lets you save program output, log information, and store results.
This guide covers everything from basic writes to advanced file handling.
Opening a File for Writing
You must open a file before writing to it. Use the built-in open() function.
This function needs the file path and a mode. The mode tells Python your intention.
For writing, the primary mode is 'w' (write). It creates a new file or overwrites an existing one.
# Open a file for writing
file_object = open('data.txt', 'w')
# ... perform file operations ...
file_object.close() # Always close the file
Always close files with the close() method. It frees up system resources.
The write() Method
The write() method is the fundamental tool for output.
It takes a single string as an argument and writes it to the file.
It does not add a newline character automatically. You must include '\n' if needed.
# Writing a string to a file
file = open('example.txt', 'w')
file.write('Hello, World!')
file.write(' This is on the same line.\n') # Added newline
file.write('Now this is on a new line.')
file.close()
After running this, the 'example.txt' file will contain the specified text.
The writelines() Method
To write multiple strings efficiently, use writelines().
It accepts an iterable (like a list) of strings. Like write(), it doesn't add newlines.
# Writing a list of strings
lines_to_write = ['First line.\n', 'Second line.\n', 'Third line.\n']
file = open('lines.txt', 'w')
file.writelines(lines_to_write)
file.close()
# Content of lines.txt
First line.
Second line.
Third line.
Essential File Modes
Choosing the right mode prevents data loss. Here are the key modes for writing.
'w' (Write): Creates a new file. Overwrites if the file exists.
'a' (Append): Opens the file for writing. New data is added to the end. It does not erase old content.
'x' (Exclusive Creation): Creates a new file. Fails with an error if the file already exists. This is safe for preventing overwrites.
'b' (Binary): Used with another mode (like 'wb'). It writes data in binary format, crucial for images or non-text files.
# Example of append mode
file = open('log.txt', 'a')
file.write('New log entry at 12:00\n')
file.close() # This adds to the file without deleting old logs
The Superior with Statement
Manually closing files is error-prone. The with statement is the best practice.
It automatically closes the file when the block ends, even if an error occurs.
# Using the with statement for safe file handling
with open('safe_example.txt', 'w') as file:
file.write('This file will be closed automatically.\n')
file.write('No need to call file.close().')
# File is safely closed here
This method is cleaner and prevents resource leaks.
Writing Different Data Types
Files store strings. To write numbers or other objects, you must convert them first.
Use the str() function or formatted string literals (f-strings).
# Writing numbers and variables
score = 95
name = 'Alice'
with open('results.txt', 'w') as f:
f.write('Player: ' + name + '\n') # Concatenation
f.write('Score: ' + str(score) + '\n') # Convert number to string
f.write(f'Formatted: {name} scored {score} points.\n') # f-string
# Content of results.txt
Player: Alice
Score: 95
Formatted: Alice scored 95 points.
Common Errors and Solutions
Beginners often face a few common issues when writing files.
FileNotFoundError: This happens if the directory path for the file does not exist. Ensure the folder exists before opening a file in 'w', 'a', or 'x' mode.
UnicodeEncodeError: Occurs when trying to write non-ASCII characters (like emojis) without specifying encoding. Always open text files with an encoding, typically encoding='utf-8'.
# Best practice: Specify encoding for text files
with open('unicode_example.txt', 'w', encoding='utf-8') as file:
file.write('Hello World! 🌍\n')
Accidental Overwrite: Using 'w' mode on an existing file erases it. Double-check your mode. Use 'a' to add or 'x' to be safe.
Conclusion
Writing to a file in Python is straightforward with the write() and writelines() methods.
Remember to use the with statement for automatic and safe file handling.
Choose your file mode carefully: 'w' to write new content, 'a' to append, and 'x' for exclusive creation.
Always specify encoding='utf-8' for text files to avoid character issues.
Mastering these concepts allows you to persistently save your program's data effectively.