Writing Files
In this tutorial, we'll create or replace text files with write mode.
Writing a file means creating or replacing file contents.
Use "w" mode:
with open("message.txt", "w") as file:
file.write("Hello\n")
file.write("This is a file\n")
If message.txt does not exist, Python creates it. If it already exists, Python replaces its contents.
Writing Variables
name = "Ada"
score = 95
with open("report.txt", "w") as file:
file.write(f"Name: {name}\n")
file.write(f"Score: {score}\n")
F-strings are very useful when writing files.
Remember Newlines
write() does not automatically add a new line:
file.write("Line one")
file.write("Line two")
This produces:
Line oneLine two
Add \n yourself:
file.write("Line one\n")
file.write("Line two\n")
Common Mistake
Do not use "w" if you want to keep the old contents. Use append mode ("a") instead.
Check the File Afterwards
After writing, open the file in your editor and inspect it. This helps you catch missing newlines or unexpected formatting.
You can also read it back with Python:
with open("profile.txt", "r") as file:
print(file.read())
Write One String or Many
You can write one prepared string:
content = "Line one\nLine two\n"
with open("example.txt", "w") as file:
file.write(content)
Or you can call write() several times. Choose whichever makes the code easier to read.
Practice
Write a file called profile.txt containing your name, current goal, and favourite Python topic.