Last modified: Feb 14, 2026 By Alexander Williams
Python Print to Text File Guide
You often use print() to show output on the screen. But you can also send that output directly to a file. This is very useful. It helps you save data, create logs, or store results for later.
This guide will show you how. We will cover the basic and advanced ways to write text files in Python.
Why Write to a Text File?
Writing to a file is a key skill. It lets you save information permanently. Your program's output is not lost when you close the terminal.
Common uses include saving program logs, exporting data, or creating reports. It is a fundamental part of working with data in Python.
The Basic Method: Using the `print()` Function
The simplest way is to use the print() function. You add a `file` argument. This tells Python where to send the text.
First, you must open a file. Use the open() function. You open it in write mode (`'w'`) or append mode (`'a'`).
# Open a file for writing. 'w' mode creates a new file or overwrites an existing one.
file = open('output.txt', 'w')
# Use the print function, specifying the 'file' argument.
print("Hello, this text goes to the file.", file=file)
print("This is a second line.", file=file)
# Always close the file to save changes and free resources.
file.close()
After running this, a file named `output.txt` will be created. It will contain the two lines of text.
Hello, this text goes to the file.
This is a second line.
The Best Practice: Using `with` Statement
Manually opening and closing files can lead to errors. You might forget to close it. The `with` statement handles this automatically.
It is the recommended way to work with files in Python. The file is closed for you when the block ends.
# Using the 'with' statement for safe file handling.
with open('data_log.txt', 'w') as file:
print("Log Entry: Program Started", file=file)
print("Timestamp: 2023-10-27", file=file)
# The file is automatically closed here.
Appending vs. Writing
You have two main modes for opening a text file.
Write Mode (`'w'`): This creates a new file. If the file already exists, it is completely erased first. Use this for new data.
Append Mode (`'a'`): This adds new text to the end of an existing file. The old content is kept safe. It is perfect for logs.
# Example of appending to a log file.
with open('application.log', 'a') as log_file:
print("INFO: User logged in.", file=log_file)
print("WARNING: Disk space low.", file=log_file)
Writing Multiple Lines and Variables
You can write any data that print() can handle. This includes variables, numbers, and formatted strings.
user = "Alice"
score = 95
items = ["apple", "banana", "cherry"]
with open('results.txt', 'w') as f:
print(f"User: {user}", file=f)
print(f"Final Score: {score}", file=f)
print("Items purchased:", *items, file=f) # Unpacking the list
User: Alice
Final Score: 95
Items purchased: apple banana cherry
Controlling the Output Format
The print() function has useful parameters. You can control the separator and line endings in the file.
The `sep` parameter defines what goes between multiple items. The `end` parameter defines what is printed at the end of the line.
with open('formatted.txt', 'w') as f:
# Change separator to a comma and space
print("Python", "Java", "C++", sep=", ", file=f)
# Change line ending to two newlines
print("End of Section", end="\n\n", file=f)
print("New Section Starts", file=f)
Python, Java, C++
End of Section
New Section Starts
Beyond `print()`: The `.write()` Method
Sometimes print() is too high-level. The file object has its own .write() method. It gives you more direct control.
A key difference: .write() does not automatically add a newline character. You must add `\n` yourself.
For complex text operations, understanding the underlying Python TextIOWrapper can be very helpful.
with open('direct_write.txt', 'w') as f:
f.write("This is line one.\n")
f.write("This is line two.\n")
# Writing a number requires converting it to a string first.
f.write("The answer is " + str(42) + ".\n")
Handling Errors and Special Cases
File operations can fail. The disk might be full. You might not have permission. It is good to handle these errors.
Use a `try...except` block. This makes your program robust and user-friendly.
filename = "important_data.txt"
try:
with open(filename, 'w') as file:
print("Saving critical data...", file=file)
except IOError as e:
print(f"Could not write to file {filename}. Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Practical Example: Creating a Simple Data Report
Let's combine everything. We will read some data and write a formatted report to a file.
This is a common task in data processing. For more advanced input, like getting text from pictures, see our guide on Python Text Extraction from Images.
# Sample data: List of tuples (product, price, quantity)
sales_data = [
("Laptop", 999.99, 5),
("Mouse", 24.50, 22),
("Keyboard", 75.00, 15),
]
with open('sales_report.txt', 'w') as report:
print("=" * 40, file=report)
print("SALES REPORT", file=report)
print("=" * 40, file=report)
print(f"{'Product':<15} {'Price':<10} {'Qty':<5} Total", file=report)
print("-" * 40, file=report)
total_revenue = 0
for product, price, qty in sales_data:
line_total = price * qty
total_revenue += line_total
# Format the output nicely
print(f"{product:<15} ${price:<9.2f} {qty:<5} ${line_total:>7.2f}", file=report)
print("-" * 40, file=report)
print(f"TOTAL REVENUE: ${total_revenue:>24.2f}", file=report)
print("=" * 40, file=report)
========================================
SALES REPORT
========================================
Product Price Qty Total
----------------------------------------
Laptop $999.99 5 $4999.95
Mouse $24.50 22 $539.00
Keyboard $75.00 15 $1125.00
----------------------------------------
TOTAL REVENUE: $6663.95
========================================
Conclusion
Printing to a text file in Python is simple and powerful. The main tool is the print() function with its `file` argument.
Always use the `with` statement. It manages files safely. Choose `'w'` mode for new files and `'a'` mode to add to logs.
You can format output, handle errors, and create complex reports. This skill is essential for saving data, debugging, and building useful applications.
Start by writing simple strings to a file. Then move on to variables and formatted data. You will find it is a very common and valuable task.