read(), readline() and readlines()
Three methods, and every exam paper asks you to tell them apart. The question that separates them is not “how much do they read?” but what shape is the answer — one string, one line, or a list.
1read() — the whole file, as one string
f.read() gives you everything in the file as a single string, newlines and all. Not a list, not lines — one long string.
f = open('notes.txt', 'r')
data = f.read()
f.close()
print(data)
print(type(data))
print(len(data))Python is easy to learn. A file keeps your data safe. Practice every day. <class 'str'> 74
print() adds another one. So the last line of the file is followed by an empty line. That is the file's own \n showing itself — every properly written text file has one at the end.Give read() a number and it reads that many characters instead — not words, not lines. The next call carries on from where the last one stopped:
f = open('notes.txt', 'r')
print(f.read(6))
print(f.read(10))
f.close()Python is easy t
read(10) counts everything, spaces and newlines included.2readline() — one line at a time
f.readline() reads from the pointer up to and including the next newline, then stops. Call it again and you get the next line. Printing the raw value with repr() shows the \n it kept:
f = open('notes.txt', 'r')
print(repr(f.readline()))
print(repr(f.readline()))
print(repr(f.readline()))
print(repr(f.readline()))
f.close()'Python is easy to learn.\n' 'A file keeps your data safe.\n' 'Practice every day.\n' ''
''. That is how every “read until the end” loop knows to stop — and note the difference: a blank line in the file comes back as '\n', which is one character and is not empty. Only the end of the file gives ''.3readlines() — a list of lines
f.readlines() reads the whole file like read(), but hands it back as a list: one string per line, each still carrying its \n.
f = open('notes.txt', 'r')
lines = f.readlines()
f.close()
print(lines)
print(len(lines))
for line in lines:
print(line.strip())['Python is easy to learn.\n', 'A file keeps your data safe.\n', 'Practice every day.\n'] 3 Python is easy to learn. A file keeps your data safe. Practice every day.
len(data) after read() is the number of characters — 74 for this file. len(lines) after readlines() is the number of lines — 3. Exam questions rely on you noticing which one you are holding.4Watch the pointer move
Every one of these methods reads forwards from the pointer, and leaves it wherever it stopped. That single fact explains all the surprises — especially the second read() coming back empty:
One file, opened once. Each call reads from the pointer — and leaves it somewhere new.
'Python is easy to learn.\nA file keeps your data safe.\nPractice every day.\n'
Python is easy to learn.
A file keeps your data safe.
Practice every day.
The whole file, as ONE string — newlines and all. The pointer is now at the end.
5Getting rid of the newline
Every line you read keeps its \n, and print() adds one of its own — which is why printing lines from a file gives you double spacing. Three string methods from Class 11 fix it:
f = open('notes.txt', 'r')
line = f.readline()
f.close()
print(repr(line))
print(repr(line.rstrip('\n')))
print(repr(line.strip()))'Python is easy to learn.\n' 'Python is easy to learn.' 'Python is easy to learn.'
line.strip()Takes blank space off BOTH ends — spaces, tabs and the newline. The usual choice.
line.rstrip('\n')Takes off only the newline, only at the right end. Use it when leading spaces are part of the data.
print(line, end='')Keeps the line as it is and stops print() adding a second newline. Also correct.
6Three loops that read a whole file
These do the same job. The first is the one to write; the second is the one exam papers print; the third is fine when the file is small.
f = open('notes.txt', 'r')
for line in f:
print(line.strip())
f.close()Python is easy to learn. A file keeps your data safe. Practice every day.
for line in f walks the file one line at a time without ever loading all of it. It is the shortest to write and the only one that works on a file bigger than your computer's memory.f = open('notes.txt', 'r')
line = f.readline()
while line != '':
print(line.rstrip('\n'))
line = f.readline()
f.close()Python is easy to learn. A file keeps your data safe. Practice every day.
while version needs a line to test before the first check, and another read at the bottom of the body. Forget the second one and the loop runs for ever on line one. This shape is why for line in f is worth preferring.f = open('notes.txt', 'r')
lines = f.readlines()
f.close()
for line in lines:
print(line.strip())Python is easy to learn. A file keeps your data safe. Practice every day.
7The three, side by side
| read() | readline() | readlines() | |
|---|---|---|---|
| Gives back | str | str | list of str |
| How much | the whole file | one line | the whole file |
| Keeps the \n | yes | yes | yes, in every item |
| At the end of the file | '' | '' | [] |
| With a number | read(n) — n characters | readline(n) — at most n characters of the line | — |
| Best for | counting characters, replacing text | walking a file line by line | when you want the lines as a list |
8Try it
Change read() to readline() or readlines() and run it again:
9Recap
The whole file as one string. read(n) gives n characters — spaces and newlines counted.
One line, including its \n. The next call gives the next line.
A list of strings, one per line, each keeping its \n.
Forwards, and the pointer stays where the read stopped. A second read() therefore gives ''.
A blank line is '\n', which is not empty. Only the end gives an empty string.
The shortest way to walk a file, and the only one that works on a file too big for memory.
- 1
Print a file twice in one program, using one open().
Hint · The second read() gives '' until you seek(0).
- 2
Print every line of a file with its line number in front of it.
Hint · A counter starting at 1, and line.strip() to kill the \n.
- 3
Count the characters in a file with
read(), and the lines withreadlines().Hint · Two len() calls on two different shapes of answer.
- 4
Print only the first line of a file without reading the rest of it.
Hint · One readline(), and nothing else.
What does f.read() give back?
A program calls f.read() twice. What does the second call give?
readline() returns ''. What does that mean?
notes.txt has 3 lines. What is len(f.readlines())?
Which line prints a file's lines without blank lines between them?