How to Write to a File in Python
What you’ll build or solve
You’ll write text to a file in Python using safe, common patterns.
When this approach works best
Writing to a file works well when you:
Learn Python on Mimo
- Save results from a script, like a report, logs, or processed data.
- Store user-generated content, like notes or exported text.
- Keep a simple record of events, like timestamps, errors, or progress updates.
Avoid this approach when you need many updates to the same data or concurrent writes from multiple processes. Use a database or a logging system designed for that.
Prerequisites
- Python installed
- You know what files and folders are on your computer
Step-by-step instructions
1) Open a file in the right mode
Use with open(...) so Python closes the file automatically.
Option A (most common): Overwrite with "w"
Creates the file if it does not exist. Replaces the file contents if it does.
Python
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello!\n")
Option B: Append with "a"
Creates the file if it does not exist. Adds new content to the end.
Python
with open("output.txt", "a", encoding="utf-8") as f:
f.write("Another line.\n")
What to look for: "w" clears the file first. Use "a" when you want to keep what’s already there. For portable file paths, see Example 4.
2) Write text in one go or line by line
Use write() for a single string. Use writelines() when you already have a list of strings.
Option A: Write a single string
Python
message = "First line\nSecond line\n"
with open("output.txt", "w", encoding="utf-8") as f:
f.write(message)
Option B: Write many lines
Python
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("output.txt", "w", encoding="utf-8") as f:
f.writelines(lines)
What to look for: writelines() does not add \n for you. Put newline characters into each line.
3) Handle file errors without crashing
Catching errors helps when the folder is read-only, the path is wrong, or permissions block writing.
Python
try:
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Writing safely.\n")
except PermissionError:
print("No permission to write here. Try a different folder.")
except FileNotFoundError:
print("Folder not found. Check the path.")
Examples you can copy
Example 1: Save a simple report
Python
report = [
"Daily Report\n",
"-----------\n",
"Users: 120\n",
"Signups: 18\n",
]
with open("report.txt", "w", encoding="utf-8") as f:
f.writelines(report)
Example 2: Append log lines with timestamps
Python
from datetime import datetime
timestamp = datetime.now().isoformat(timespec="seconds")
line = f"{timestamp} - job started\n"
with open("app.log", "a", encoding="utf-8") as f:
f.write(line)
Example 3: Write cleaned lines to a new file
Python
cleaned = []
with open("raw.txt", "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
cleaned.append(line + "\n")
with open("cleaned.txt", "w", encoding="utf-8") as f:
f.writelines(cleaned)
Example 4: Write a file next to your script with pathlib
This example builds a path that works even when you run the script from a different folder.
Python
from pathlib import Path
out_path = Path(__file__).with_name("output.txt")
with out_path.open("w", encoding="utf-8") as f:
f.write("This file lives next to the script.\n")
Example 5: Create a folder before writing
Python
from pathlib import Path
folder = Path("exports")
folder.mkdir(parents=True, exist_ok=True)
file_path = folder / "results.txt"
with file_path.open("w", encoding="utf-8") as f:
f.write("Saved in exports/results.txt\n")
Common mistakes and how to fix them
Mistake 1: Using "w" and accidentally overwriting a file
What you might do:
Python
with open("output.txt", "w", encoding="utf-8") as f:
f.write("New content\n")
Why it breaks: "w" clears the file first, so you lose what was already there.
Correct approach:
Python
with open("output.txt", "a", encoding="utf-8") as f:
f.write("New content\n")
Mistake 2: Forgetting newline characters
What you might do:
Python
lines = ["one", "two", "three"]
with open("output.txt", "w", encoding="utf-8") as f:
f.writelines(lines)
Why it breaks: All text runs together because Python does not add line breaks for you.
Correct approach:
Python
lines = ["one\n", "two\n", "three\n"]
with open("output.txt", "w", encoding="utf-8") as f:
f.writelines(lines)
Mistake 3: Writing to a different folder than you expect
What you might do:
Python
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Where did this go?\n")
Why it breaks: Relative paths write to the current working directory, which can differ between your IDE and terminal.
Correct approach:
Python
from pathlib import Path
file_path = Path(__file__).with_name("output.txt")
with file_path.open("w", encoding="utf-8") as f:
f.write("Now it’s next to the script.\n")
Troubleshooting
If you see PermissionError, try writing to a folder you own, like your home directory, or choose a different output path.
If you see FileNotFoundError, the folder in the path does not exist. Create it first, as shown in Example 5.
If you can’t find the file, print the working directory:
Python
import os
print(os.getcwd())
If your file has strange characters, set encoding="utf-8" when writing and reading.
If you see missing lines in a log, check that you used "a" for append and included \n.
Quick recap
- Open files with
with open(...)so they close automatically. - Use
"w"to overwrite and"a"to append. - Use
write()for one string andwritelines()for many lines. - Catch
PermissionErrorand missing-folder errors when writing. - Use
pathlibwhen you need a predictable output location.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot