Before you run it, say out loud what it will print. Then open the answer.
What it prints
7
2
Rows in that text.
text = "a\nb\n"
print(len(text.splitlines()))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
2
3
Characters written.
out = "hello"
print(len(out))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
5
4
Two writes appended.
out = "a" + "b"
print(out)
Before you run it, say out loud what it will print. Then open the answer.
What it prints
ab
Put it in order
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Data Flow
Opening with w replaces the file and a adds to it. The endings you write are the endings you choose.
1pick a mode
↓
2build the text
↓
3write it once
↓
4read it back
Line by line
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
rows = ["a", "b", "c"]sets nothing on screen
out = "\n".join(rows) + "\n"sets nothing on screen
print(len(out))7
Why this worksMode is a choice, not a default
w truncates and a appends. Opening with the wrong one silently destroys or grows a file, so state the mode every time.
Write once, not per line
Building the whole text and writing it in one call is simpler and lets one failure leave a whole file missing rather than half a file.
Examples
Write replaces
withopen("out.txt", "w") as f:
f.write("first")
print("done")
Mode w truncates the file first. Anything that was there is gone.
Append adds
withopen("out.txt", "a") as f:
f.write("more")
print("done")
Mode a keeps what exists and adds after it. Use it for logs.
Newlines are yours
withopen("out.txt", "w") as f:
f.write("a\nb\n")
print("done")
write does not add an ending. Put it in the string or lines run together.
Write many lines
rows = ["a", "b", "c"]
out = "\n".join(rows) + "\n"print(len(out))
Join then write once. A loop of writes does the same with more calls.
A file that is new
withopen("new.txt", "w") as f:
f.write("hi")
print("made")
Mode w creates the file when it does not exist. It also empties it when it does.
Read back what you wrote
text = "a\nb\n"print(len(text), len(text.splitlines()))
The bytes you wrote are the bytes you read. Counting them checks the write.
Words this lesson uses
Each one is defined here on this site. Open the entry for the full definition and the other words it points at.