How to write a text file
Write new content
Mode "w" creates a file or completely replaces an existing file. Newline characters must be included explicitly.
with open("report.txt", "w", encoding="utf-8") as file:
file.write("Course report\n")
file.write("Status: complete\n")
Append content
Mode "a" adds at the end without deleting existing data. It is useful for simple logs.
from datetime import datetime
with open("activity.log", "a", encoding="utf-8") as file:
file.write(f"Started at {datetime.now()}\n")
Write several lines
writelines() does not add separators, so include newlines yourself. A generator can add them cleanly.
items = ["strings", "lists", "files"]
with open("topics.txt", "w", encoding="utf-8") as file:
file.writelines(f"{item}\n" for item in items)
Avoid accidental overwrites
Mode "x" creates a new file and raises FileExistsError if it already exists. It is safer when replacing data would be harmful.
try:
with open("settings.txt", "x", encoding="utf-8") as file:
file.write("theme=dark\n")
except FileExistsError:
print("settings.txt already exists")