How to write to a file in Python
Learn how to write to a file in Python. Explore different methods, tips, real-world examples, and how to debug common errors.

Python makes it simple to write data to a file. It's a fundamental skill for data persistence, logging, and configuration, all handled through built-in functions like open().
In this article, we'll cover the essential techniques for writing to both text and binary files. You'll get practical tips for different modes, explore real-world applications, and receive debugging advice for common errors.
Basic file writing with open() and write()
file = open("sample.txt", "w")
file.write("Hello, this is a sample text file.")
file.close()--OUTPUT--No visible output - creates or overwrites sample.txt with the content
The open() function is your entry point, but the mode you choose dictates its behavior. Using "w" for write mode is a key decision with two outcomes:
- If
sample.txtdoesn't exist, Python creates it. - If it does exist, Python erases its contents before writing the new data.
After adding content with write(), you must call close(). This step is non-negotiable as it finalizes the write operation by flushing the internal buffer to the file and releasing the system resource.
Common file writing techniques
Beyond the basic open() and close() pattern, Python provides safer and more efficient techniques for handling common file writing operations.
Using the with statement for safer file handling
with open("sample.txt", "w") as file:
file.write("Hello, this is a sample text file.")--OUTPUT--No visible output - file is automatically closed after the with block
The with statement is the modern, recommended way to handle files. It simplifies resource management by creating a context that automatically calls close() for you, so you don't have to remember to do it yourself. This pattern is often called a context manager.
- It guarantees the file is closed properly, even if an error occurs inside the
withblock. - This makes your code cleaner and less prone to resource leak bugs.
Appending content to existing files
with open("sample.txt", "a") as file:
file.write("\nThis line is appended to the file.")--OUTPUT--No visible output - adds new content to the end of sample.txt
When you need to add data to a file without deleting its existing contents, you'll use append mode. Just switch the mode in open() from "w" to "a". This tells Python to move the file pointer to the very end before writing.
- If the file doesn't exist, append mode creates it for you.
The \n in the write() call is a newline character. It ensures your appended text starts on a fresh line instead of being tacked onto the last one.
Writing multiple lines at once with writelines()
lines = ["First line", "Second line", "Third line"]
with open("sample.txt", "w") as file:
file.writelines([line + "\n" for line in lines])--OUTPUT--No visible output - creates file with multiple lines of text
For writing a list of strings to a file, writelines() is a handy shortcut. It takes an iterable—like the lines list in the example—and writes all its items to the file, which is often more efficient than calling write() in a loop.
- One key detail is that
writelines()doesn't add line breaks for you. You must explicitly include newline characters (\n) with each string to ensure every item appears on its own line.
Advanced file writing operations
While write() and writelines() are great for text, you'll often need more specialized tools for structured data or more modern approaches to file system paths.
Writing structured data to JSON files
import json
data = {"name": "John", "age": 30, "city": "New York"}
with open("data.json", "w") as json_file:
json.dump(data, json_file, indent=4)--OUTPUT--No visible output - creates data.json with formatted JSON content
When you're working with structured data like Python dictionaries, JSON is the standard format for storing and exchanging it. Python's built-in json module handles the conversion for you. The json.dump() function serializes your Python object and writes it directly to a file.
- The first argument is your data object, and the second is the file object.
- Adding
indent=4is a great touch—it formats the output with spaces, making the resulting JSON file much easier for humans to read.
Using the print() function to write to files
with open("output.txt", "w") as file:
print("Line 1", file=file)
print("Line 2", file=file)
print("Numbers:", 1, 2, 3, sep=", ", file=file)--OUTPUT--No visible output - creates output.txt with formatted content
You can also use the familiar print() function to write to a file. By passing the file object to its file parameter, you redirect its output from the console. This method is convenient because print() automatically adds a newline after each call, so you don't have to manually add \n.
- It seamlessly converts non-string objects to strings before writing.
- You can use other
print()parameters, likesep, to format the output, such as adding commas between numbers.
Modern file handling with the pathlib module
from pathlib import Path
path = Path("modern_file.txt")
path.write_text("Writing files with pathlib is cleaner and modern.")--OUTPUT--73 # Returns the number of characters written
The pathlib module offers a modern, object-oriented way to handle file system paths. Instead of treating paths as simple strings, you create a Path object. This bundles path-related logic into a clean interface that works consistently across different operating systems.
The write_text() method is a convenient shortcut that handles the entire file writing process for you.
- It replaces the need for a
with open(...)block for simple text writing. - It automatically opens, writes to, and closes the file.
- It defaults to UTF-8 encoding, which prevents many common character-related bugs.
Move faster with Replit
Replit is an AI-powered development platform that lets you start coding Python instantly. It comes with all dependencies pre-installed, so you can skip the setup and get straight to building.
While knowing how to write to a file is a key skill, Agent 4 helps you leap from individual techniques to building complete applications. Instead of piecing together functions, you can describe the app you want, and the Agent will take it from an idea to a working product.
- A log file generator that takes a list of system events and writes them to a text file, each on a new line.
- A user profile exporter that serializes a dictionary of user data into a formatted JSON file for backup or transfer.
- A batch content creator that generates multiple text files from a list of titles, each containing a basic content template.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even simple file operations can lead to tricky errors, but most have straightforward solutions.
Fixing path errors when writing to non-existent directories
A common tripwire is the FileNotFoundError, which pops up when your code tries to write a file into a directory that doesn't exist. The open() function is smart enough to create a file, but it won't build the folder structure for you.
The following code demonstrates what happens when you attempt to write to a path like new_folder/data.txt before the new_folder directory has been created.
# Trying to write to a file in a directory that doesn't exist
file = open("new_folder/data.txt", "w")
file.write("This will cause an error")
file.close()
The open() function triggers an error because the new_folder directory doesn't exist, and Python won't create the missing folder for you. Check out the code below for the correct way to manage this.
import os
# Create directory first if it doesn't exist
os.makedirs("new_folder", exist_ok=True)
file = open("new_folder/data.txt", "w")
file.write("This works correctly")
file.close()
The solution is to create the directory path before attempting to write the file. You can do this with the os.makedirs() function, which builds the necessary directory structure for you.
- Setting
exist_ok=Trueis crucial—it prevents an error if the folder already exists, making your script safe to run multiple times.
Once the directory is in place, your open() call will succeed. You'll often encounter this when generating log files or user data exports into organized folders.
Handling type errors with write() function
The write() function is particular—it only accepts string data. If you try to pass a list of numbers or any other non-string object directly, Python will stop with a TypeError. This is a common hurdle. The following code demonstrates this exact issue.
numbers = [1, 2, 3, 4, 5]
with open("numbers.txt", "w") as file:
file.write(numbers) # TypeError: write() argument must be str, not list
The write() function can't handle the numbers list directly, which triggers the error. To fix this, you need to process the list before writing it to the file. See the correct approach in the code below.
numbers = [1, 2, 3, 4, 5]
with open("numbers.txt", "w") as file:
file.write(str(numbers)) # Converts list to string representation
# Or to write each number on a new line:
# file.write("\n".join(str(num) for num in numbers))
To fix the TypeError, you must convert your data to a string before writing, as the write() function doesn't do it for you. You have a couple of options:
- You can wrap the entire object in
str(), likestr(numbers), to write its literal string representation. - For more control, you can iterate through the list, convert each item to a string, and join them.
Keep an eye out for this error when logging numerical data or saving complex objects.
Solving character encoding issues with special characters
Character encoding issues often appear when your code moves between operating systems or handles text with special characters like ä or €. Python's default encoding isn't always universal, which can lead to a UnicodeEncodeError when a character isn't supported. The following code demonstrates this problem.
text = "Special characters: äöü߀"
with open("special_chars.txt", "w") as file:
file.write(text) # May cause UnicodeEncodeError with default encoding
The open() function defaults to a system-specific encoding. If that encoding doesn't support characters like ä or €, the write() operation will fail. The corrected code below demonstrates how to prevent this ambiguity.
text = "Special characters: äöü߀"
with open("special_chars.txt", "w", encoding="utf-8") as file:
file.write(text) # Properly handles special characters
The fix is to explicitly set the character encoding. By adding the encoding="utf-8" parameter to your open() call, you instruct Python to use a universal standard that handles virtually any character.
- This simple addition makes your code portable and prevents errors when writing text with accents, symbols, or emojis.
It's a crucial habit to adopt whenever you're working with data from international sources, user input, or web APIs.
Real-world applications
With a solid grasp of error handling, you can now use these techniques to build practical tools for logging and data exporting.
Creating a simple logging system with append mode
You can build a straightforward logging system by opening a file in "a" mode, which safely adds new records without disturbing the existing content.
def log_activity(action):
from datetime import datetime
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("app_log.txt", "a") as log_file:
log_file.write(f"[{timestamp}] {action}\n")
log_activity("User logged in")
log_activity("Data processed successfully")
The log_activity function packages the logging logic into a reusable tool, designed to create a clean, chronological record of events in app_log.txt.
- It captures the precise moment an action occurs using
datetime.now(). - An f-string neatly formats each log entry by combining the timestamp with the custom
actionmessage. - The
\ncharacter ensures every new log entry starts on a fresh line, keeping the file organized and readable.
Exporting data to CSV files with the csv module
To export tabular data for spreadsheet applications, Python's csv module provides a writer object that handles formatting and writing each row correctly.
import csv
sales_data = [
["Product", "Quantity", "Price"],
["Laptop", 5, 1200],
["Mouse", 10, 25],
["Keyboard", 7, 60]
]
with open("sales_data.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerows(sales_data)
This code uses Python's csv module to turn a list of lists into a properly formatted CSV file. The csv.writer object is created to handle the conversion of your Python data into comma-separated strings that spreadsheet programs can understand.
- The
writer.writerows()method is an efficient way to write all the data from thesales_datalist at once. - Including
newline=""when opening the file is a crucial detail. It prevents Python from inserting extra blank rows, ensuring your CSV file is clean and correctly structured.
Get started with Replit
Turn your knowledge into a real tool. Ask Replit Agent to “build a simple logger that appends user actions to a text file” or “create a tool that exports a dictionary of settings to a JSON file.”
The Agent writes the code, tests for errors, and deploys the app, handling the entire development cycle automatically. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

.png)
.png)
.png)