Writing and adding to files
🌍 In real life. A shop has two kinds of notebook page. On a fresh sheet for today's prices, you rub out whatever was there and write anew. In the sales diary, you never rub anything out: each sale is added at the bottom. Pick the wrong one, and you either lose yesterday's sales or end up with old prices mixed with new.
Python's file modes are those two pages: "w" and "a".
The idea in one sentence: open(name, "w") starts the file empty and writes from the beginning, open(name, "a") keeps what's there and adds to the end, and f.write(text) writes exactly the text you give it.
Its words:
- mode: the second argument of
open:"r"read (the default),"w"write,"a"append f.write(text): writes a string, with no newline unless you add\nprint(..., file=f): prints into the file instead, adding the newline for you
Step by step, for "w" on a file holding "old":
- Opening with
"w"empties the file at once: "old" is gone. f.write("hi\n")writes the first line.f.write("yo\n")writes the next one, after it.
with open("todo.txt", "w") as f:
f.write("buy milk\n")
f.write("call Bo\n")
with open("todo.txt", "a") as f:
f.write("water plants\n")
with open("todo.txt") as f:
print(f.read())print can write to a file too, with file=f, and it adds the \n for you. Here, every Run starts with only the files shown with the editor, so a file your program writes is gone after the run.
names = ["Ana", "Bo", "Cy"]
with open("names.txt", "w") as f:
for name in names:
print(name, file=f)
with open("names.txt") as f:
print(f.readlines())Why are writes kept until the end? Python collects what you write in memory and passes it to the file in larger pieces, which is much faster than one tiny write at a time. Closing the file (the end of the with block) makes sure everything has really been written.
Mistakes and edge cases.
- "w" when you meant "a". It empties the file the moment it opens, before you write anything.
- Writing a number.
f.write(5)givesTypeError: write() argument must be str, not int. Writestr(5), or useprint(5, file=f). - Forgetting \n.
f.write("a")thenf.write("b")makes one line, "ab". - Writing to a file opened for reading.
open(name)reads only:f.write(...)givesio.UnsupportedOperation: not writable.
Quiz
What does this print?
with open("a.txt", "w") as f: f.write("first\n") with open("a.txt", "w") as f: f.write("second\n") with open("a.txt") as f: print(f.read().strip())What does this print?
with open("a.txt", "w") as f: f.write("first\n") with open("a.txt", "a") as f: f.write("second\n") with open("a.txt") as f: print(len(f.readlines()))What does this print?
with open("a.txt", "w") as f: f.write("a") f.write("b") with open("a.txt") as f: print(f.read())Which mode keeps a file's lines and adds new ones at the end?
- "a"
- "w"
- "r"
Which line has a mistake?
with open("log.txt", "w") as f: f.write("start\n") with open("log.txt") as f: f.write("more\n")
Coding tasks
Write
save_lines(lines, filename)that writes each item of the list on its own line in the file (replacing what was there).log.txtalready has some lines. Add the linedoneto the end of it, keeping what's there.Write
copy_upper(src, dst)that writes the text of file src, in capitals, to file dst.