After this lesson you will be able to save text from a program into a file, add new lines to an existing file without losing what is already there, and check what you wrote. This is how programs keep results after they finish.
Creating a file with mode "w"
open() takes a second argument, the mode. Mode "w" means write. It creates the file if it does not exist. If the file does exist, it is emptied the moment it is opened.
with open("report.txt", "w", encoding="utf-8") as f:
f.write("Daily sales report\n")
f.write("Pens: 40\n")
f.write("Notebooks: 15\n")
with open("report.txt", encoding="utf-8") as f:
print(f.read())Daily sales report
Pens: 40
Notebooks: 15Look at the \n at the end of each string. write() writes exactly what you give it and nothing more, so you must supply the line breaks. Here is what happens without them:
with open("run-together.txt", "w", encoding="utf-8") as f:
f.write("Pens")
f.write("Ink")
with open("run-together.txt", encoding="utf-8") as f:
print(f.read())PensInkOverwriting is silent
Opening with "w" again wipes the earlier contents without any warning.
with open("report.txt", "w", encoding="utf-8") as f:
f.write("Only this line is left\n")
with open("report.txt", encoding="utf-8") as f:
print(f.read())Only this line is leftWhen the old text matters, use a different mode or write to a new file name.
Adding to the end with mode "a"
Mode "a" is append. The file is created if needed, and new text goes after what is already there.
with open("log.txt", "a", encoding="utf-8") as f:
f.write("Shop opened\n")
with open("log.txt", "a", encoding="utf-8") as f:
f.write("First sale\n")
with open("log.txt", encoding="utf-8") as f:
print(f.read())Shop opened
First saleEach run of a program would add more lines, which is exactly what you want for a log.
Modes at a glance
| Mode | Meaning | If the file exists | If it does not exist |
|---|---|---|---|
"r" |
Read (the default) | Opened for reading | FileNotFoundError |
"w" |
Write | Emptied, then written | Created |
"a" |
Append | New text goes at the end | Created |
"x" |
Create only | FileExistsError |
Created |
The "x" mode is a safety net. If you want to be sure you never destroy something, use it and handle the error:
try:
with open("report.txt", "x", encoding="utf-8") as f:
f.write("new report\n")
except FileExistsError:
print("report.txt already exists, nothing written")report.txt already exists, nothing writtenWriting many lines
Loop and write one line at a time, or use print with the file argument, which adds the newline for you:
students = ["Asha", "Ben", "Chloe"]
with open("students.txt", "w", encoding="utf-8") as f:
for number, name in enumerate(students, start=1):
print(f"{number}. {name}", file=f)
with open("students.txt", encoding="utf-8") as f:
print(f.read(), end="")1. Asha
2. Ben
3. Chloewritelines() writes a list of strings in one go, but it also adds no newlines, so include them yourself:
items = ["Pens", "Ink", "Paper"]
with open("items.txt", "w", encoding="utf-8") as f:
f.writelines(item + "\n" for item in items)
with open("items.txt", encoding="utf-8") as f:
print(f.read().splitlines())['Pens', 'Ink', 'Paper']Only strings can be written
In text mode write() accepts strings only. Numbers must be converted first:
with open("count.txt", "w", encoding="utf-8") as f:
f.write(42)TypeError: write() argument must be str, not intwith open("count.txt", "w", encoding="utf-8") as f:
f.write(str(42))
f.write(f"\n{40 + 2} again\n")
with open("count.txt", encoding="utf-8") as f:
print(f.read(), end="")42
42 againWhy with matters even more for writing
Python may keep written text in memory for a moment before it reaches the disk. Closing the file pushes it out. The with block closes the file for you, even if an error occurs halfway, so you keep what was written so far. If you ever open a file without with, you must call f.close() yourself.
Common mistakes
- Opening with
"w"when you meant"a". The earlier contents are gone. Pick the mode deliberately. - Forgetting
\n. Everything lands on one line. Add the newline, or useprint(..., file=f). - Writing a number directly. Convert it with
str()or an f-string. - Reading a file you are still writing. Close it, or leave the
withblock, before opening it again for reading. - Opening a file for reading and writing it. Mode
"r"cannot write. The error isio.UnsupportedOperation: not writable.
Exercise
Write a program that creates shopping.txt containing three items, one per line. Then append a fourth item, and finally read the file back and print how many lines it has.
Show one possible answer
with open("shopping.txt", "w", encoding="utf-8") as f:
for item in ["bread", "milk", "rice"]:
f.write(item + "\n")
with open("shopping.txt", "a", encoding="utf-8") as f:
f.write("tea\n")
with open("shopping.txt", encoding="utf-8") as f:
lines = f.read().splitlines()
print(lines)
print(len(lines), "lines")['bread', 'milk', 'rice', 'tea']
4 linesNext: CSV and JSON covers two common file formats for storing structured data. A video version of this topic is in the video course at /learn/python/.
Key points
- open(name, 'w') creates the file or empties an existing one, 'a' adds to the end, and 'x' fails if the file already exists.
- write() does not add a newline. You add \n yourself, or use print(..., file=f).
- writelines() writes an iterable of strings but also does not add newlines.
- write() only accepts strings, so convert numbers with str() or an f-string.
- Using with closes the file and makes sure your data is saved.