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.
LUA
withopen("output.txt","w",encoding="utf-8")asf:
f.write("Hello!\n")
Option B: Append with "a"
Creates the file if it does not exist. Adds new content to the end.
LUA
withopen("output.txt","a",encoding="utf-8")asf:
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
message="First line\nSecond line\n"
withopen("output.txt","w",encoding="utf-8")asf:
f.write(message)
Option B: Write many lines
Swift
lines= ["First line\n","Second line\n","Third line\n"]
withopen("output.txt","w",encoding="utf-8")asf:
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.
CSS
try:
withopen("output.txt","w",encoding="utf-8")asf:
f.write("Writing safely.\n")
exceptPermissionError:
print("No permission to write here. Try a different folder.")
exceptFileNotFoundError:
print("Folder not found. Check the path.")
Examples you can copy
Example 1: Save a simple report
Swift
report= [
"Daily Report\n",
"-----------\n",
"Users: 120\n",
"Signups: 18\n",
]
withopen("report.txt","w",encoding="utf-8")asf:
f.writelines(report)
Example 2: Append log lines with timestamps
fromdatetimeimportdatetime
timestamp=datetime.now().isoformat(timespec="seconds")
line=f"{timestamp} - job started\n"
withopen("app.log","a",encoding="utf-8")asf:
f.write(line)
Example 3: Write cleaned lines to a new file
cleaned= []
withopen("raw.txt","r",encoding="utf-8")asf:
forlineinf:
line=line.strip()
ifline:
cleaned.append(line+"\n")
withopen("cleaned.txt","w",encoding="utf-8")asf:
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.
frompathlibimportPath
out_path=Path(__file__).with_name("output.txt")
without_path.open("w",encoding="utf-8")asf:
f.write("This file lives next to the script.\n")
Example 5: Create a folder before writing
frompathlibimportPath
folder=Path("exports")
folder.mkdir(parents=True,exist_ok=True)
file_path=folder/"results.txt"
withfile_path.open("w",encoding="utf-8")asf:
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:
LUA
withopen("output.txt","w",encoding="utf-8")asf:
f.write("New content\n")
Why it breaks: "w" clears the file first, so you lose what was already there.
Correct approach:
LUA
withopen("output.txt","a",encoding="utf-8")asf:
f.write("New content\n")
Mistake 2: Forgetting newline characters
What you might do:
lines= ["one","two","three"]
withopen("output.txt","w",encoding="utf-8")asf:
f.writelines(lines)
Why it breaks: All text runs together because Python does not add line breaks for you.
Correct approach:
Swift
lines= ["one\n","two\n","three\n"]
withopen("output.txt","w",encoding="utf-8")asf:
f.writelines(lines)
Mistake 3: Writing to a different folder than you expect
What you might do:
LUA
withopen("output.txt","w",encoding="utf-8")asf:
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:
frompathlibimportPath
file_path=Path(__file__).with_name("output.txt")
withfile_path.open("w",encoding="utf-8")asf:
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:
LUA
importos
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