Lesson 2 of 9
The with statement
You saw .close() in the last lesson. Forgetting it is a real bug — data can sit unwritten in a
buffer, and the file stays locked.
with closes the file for you, automatically, even if an error is raised inside the block:
with open("notes.txt", "w") as f:
f.write("Hello, file!")
print("File is closed now.")
Read that as "open this file as f, and close it when the indented block ends." Always use
with — the manual open()/.close() pair is only worth knowing so you recognise it in older
code.
with is a context manager. Module 9 shows how to write your own.
Writing
"w" mode completely overwrites the file. This is the most common way beginners lose data:
with open("log.txt", "w") as f:
f.write("First run\n")
with open("log.txt", "w") as f:
f.write("Second run\n")
with open("log.txt") as f:
print(f.read().strip())
Only "Second run" survives. If the file exists, "w" empties it the moment it opens.
Appending
"a" adds to the end instead:
with open("log.txt", "w") as f:
f.write("First run\n")
with open("log.txt", "a") as f:
f.write("Second run\n")
with open("log.txt") as f:
print(f.read().strip())
Use "w" to replace a file, "a" to add to a log.
.write() doesn't add newlines
Unlike print(), .write() writes exactly what you give it:
with open("out.txt", "w") as f:
f.write("one")
f.write("two")
with open("out.txt") as f:
print(f.read())
That produces onetwo on a single line. Add \n yourself.
Writing a list
.writelines() writes every string in a list — again, adding no newlines of its own:
lines = ["apple\n", "banana\n", "cherry\n"]
with open("fruits.txt", "w") as f:
f.writelines(lines)
with open("fruits.txt") as f:
print(f.read().strip())
A loop is often clearer, and lets you add the newline as you go:
fruits = ["apple", "banana", "cherry"]
with open("fruits.txt", "w") as f:
for fruit in fruits:
f.write(f"{fruit}\n")
with open("fruits.txt") as f:
print(f.read().strip())
Opening several files
One with can manage more than one file — handy for reading from one and writing to another:
with open("source.txt", "w") as f:
f.write("hello\nworld\n")
with open("source.txt") as src, open("upper.txt", "w") as dst:
for line in src:
dst.write(line.upper())
with open("upper.txt") as f:
print(f.read().strip())
Try it yourself
Write a list of fruits, append one more, then read the file back.
Checkpoint
with open(...) as f:closes the file automatically — always prefer it."w"overwrites from scratch;"a"appends..write()adds no newline; include\nyourself.- One
withcan open several files, separated by commas.
Questions about this lesson
Log in to ask a question.