livepython.net
CHAPTER 19File Handling
19.3  READ

Python Read File: read(), readline() and Lines

Read a Whole File with read()

The read() method gives you the whole file as one string. Every line is in it, with a "\n" wherever a line ends.

Think of it like reading a whole letter in one go, instead of one sentence at a time. You get everything at once, and then you can do what you like with it.

The rules

  • Open the file in mode "r" (or with no mode), then call f.read().
  • It gives back a string, so store it: text = f.read().
  • Every string method from chapter 12 works on it: upper(), count(), replace(), split()...
  • An empty file gives back "", the empty string.
PYTHONedit me
f = open("poem.txt", "w")
f.write("Roses are red\n")
f.write("Violets are blue\n")
f.close()

f = open("poem.txt", "r")
text = f.read()
f.close()

print(text)
print(len(text))
print(text.count("are"))
OUTPUT
Roses are red
Violets are blue

31
2

len(text) is 31: 29 letters and spaces, plus the two "\n" characters. Yes, a newline counts as a character. And there's an empty line after the poem: the file's last "\n", then the new line print() adds.

Reading a second time

A file remembers how far you've read, like a bookmark. After read(), the bookmark is at the very end. So a second read() finds nothing left:

PYTHONedit me
f = open("poem.txt", "w")
f.write("Roses are red")
f.close()

f = open("poem.txt")
first = f.read()
second = f.read()
f.close()

print(first)
print(len(second))
OUTPUT
Roses are red
0

Good: read once, keep it

Store the text in a variable and use the variable as often as you like. To read the file from the start again, close it and open it again.

Common beginner doubt: "Is read() OK for a big file?" For the small text files in this course, yes. A huge file would fill your computer's memory, and then you'd read it line by line. That's two lessons from now.

read() gives you the whole file as one string, newlines and all. Read once and keep it.

your turnPredict the output

What will this print?

f = open("pet.txt", "w") f.write("Lucky") f.close() f = open("pet.txt") print(f.read().upper()) print(f.read()) f.close()
Your turn! What will this code show on the screen?
your turnType the output

Type what this prints

f = open("hi.txt", "w") f.write("Hi\n") f.close() f = open("hi.txt") print(len(f.read())) f.close()
Read the code line by line, then type the output exactly.

Read One Line with readline() and readlines()

The readline() method reads just the next line of a file, including the "\n" at its end. Call it again, and you get the line after that. Its cousin readlines() gives you all the lines at once, as a list.

Think of it like a bookmark that moves down a page. Each readline() reads one line and moves the bookmark to the start of the next one.

The rules

You writeYou get
f.readline()the next line as a string, with its "\n"
f.readline() at the end"", the empty string
f.readlines()a list of all the (remaining) lines, each with its "\n"
PYTHONedit me
f = open("players.txt", "w")
f.write("Sunny\nRocky\nLucky\n")
f.close()

f = open("players.txt")
first = f.readline()
second = f.readline()
f.close()

print(first.strip())
print(second.strip())
OUTPUT
Sunny
Rocky

strip() from chapter 12 takes the "\n" off the end of each line.

Avoid: printing a line with its newline

PYTHONedit me
f = open("players.txt", "w")
f.write("Sunny\nRocky\n")
f.close()

f = open("players.txt")
print(f.readline())
print(f.readline())
f.close()
OUTPUT
Sunny

Rocky

An empty line sneaks in between the names. The line's own "\n" ends it, and then print() adds another one.

readlines() gives a list

PYTHONedit me
f = open("players.txt", "w")
f.write("Sunny\nRocky\nLucky\n")
f.close()

f = open("players.txt")
lines = f.readlines()
f.close()

print(lines)
print(len(lines), "players")
print(lines[-1].strip())
OUTPUT
['Sunny\n', 'Rocky\n', 'Lucky\n']
3 players
Lucky

It's a normal list (chapter 9), so len(), indexes and slices all work on it.

Common beginner doubt: "When do I use readline()?" When you only need the first line or two, like a title at the top of a file. For every line, the for loop in the next lesson is easier.

readline() reads the next line; readlines() gives a list of lines. Both keep the "\n".

your turnFill the gap

Print the first line, with no empty line after it

f = open("menu.txt", "w") f.write("Pizza\nPasta\n") f.close() f = open("menu.txt") line = f.readline() f.close() print(line.?())

It should print: Pizza

Which piece makes this code work?
your turnPredict the output

What will this print?

f = open("abc.txt", "w") f.write("a\nb\nc\n") f.close() f = open("abc.txt") f.readline() print(f.readline().strip()) f.close()
Your turn! What will this code show on the screen?

Loop Over the Lines of a File

A file works in a for loop, like a list: for line in f: gives you one line each turn, from the first to the last. It's the most common way to read a file in Python.

Think of it like a conveyor belt at the airport. The bags come past one at a time, and you pick up each one as it reaches you, until the belt is empty.

The rules

  • for line in f: loops over the lines in order.
  • Each line still ends with "\n", so line.strip() it before you use it.
  • Inside the loop you can do anything from earlier chapters: print, count, check with if, add to a list.
PYTHONedit me
f = open("shopping.txt", "w")
f.write("bread\nmilk\neggs\n")
f.close()

f = open("shopping.txt")
for line in f:
    item = line.strip()
    print("Buy:", item)
f.close()
OUTPUT
Buy: bread
Buy: milk
Buy: eggs

Avoid: forgetting strip()

PYTHONedit me
f = open("shopping.txt", "w")
f.write("bread\nmilk\n")
f.close()

f = open("shopping.txt")
for line in f:
    print(line + "!")
f.close()
OUTPUT
bread
!
milk
!

The ! lands on its own line, because it comes after the line's "\n".

Good: strip, then use

PYTHONedit me
f = open("shopping.txt", "w")
f.write("bread\nmilk\n")
f.close()

f = open("shopping.txt")
for line in f:
    print(line.strip() + "!")
f.close()
OUTPUT
bread!
milk!

Load the lines into a list

Loop, strip, and append() (chapter 9), and the file becomes a clean list of strings:

PYTHONedit me
f = open("shopping.txt", "w")
f.write("bread\nmilk\neggs\n")
f.close()

items = []
f = open("shopping.txt")
for line in f:
    items.append(line.strip())
f.close()

print(items)
print("milk" in items)
OUTPUT
['bread', 'milk', 'eggs']
True

Common beginner doubt: "readlines() gives me a list too. Why loop?" readlines() keeps every "\n". The loop lets you clean each line on the way in, and it reads one line at a time, so it works for huge files as well.

for line in f: reads a file line by line. strip() each line before you use it.

your turnOrder the lines

Put the lines in order to print each name in capitals

  1. f = open("crew.txt")
  2. print(line.strip().upper())
  3. f.write("sunny\nrocky\n")
  4. for line in f:
  5. f.close()
  6. f = open("crew.txt", "w")
These lines are mixed up. Put them back in order, then press Check.
your turnPredict the output

What will this print?

f = open("nums.txt", "w") f.write("4\n5\n") f.close() total = 0 f = open("nums.txt") for line in f: total += int(line) f.close() print(total)
Your turn! What will this code show on the screen?

Count Lines and Words in a File

Once you can loop over a file, you can count what's in it: lines, words, or lines that match something. It's the counter pattern from chapter 10, with lines from a file instead of items from a list.

Think of it like a teacher marking an essay: going down the page, keeping a tally of the lines, and of the words on each line.

The rules

  • Make each counter 0 before the loop.
  • Add 1 for every line: lines += 1.
  • line.split() (chapter 12) breaks a line into words, so len(line.split()) counts its words.
  • Use an if inside the loop to count only some lines.
PYTHONedit me
f = open("story.txt", "w")
f.write("Sunny has a cat\n")
f.write("Rocky has a dog\n")
f.write("Lucky has a fish and a cat\n")
f.close()

lines = 0
words = 0
cats = 0
f = open("story.txt")
for line in f:
    lines += 1
    words += len(line.split())
    if "cat" in line:
        cats += 1
f.close()

print("Lines:", lines)
print("Words:", words)
print("Lines with cat:", cats)
OUTPUT
Lines: 3
Words: 15
Lines with cat: 2

split() with no argument splits on spaces and ignores the "\n", so there's no need to strip first here.

Avoid: empty lines counted as lines

PYTHONedit me
f = open("story.txt", "w")
f.write("Sunny has a cat\n\nRocky has a dog\n")
f.close()

lines = 0
f = open("story.txt")
for line in f:
    lines += 1
f.close()
print("Lines:", lines)
OUTPUT
Lines: 3

The empty line in the middle is "\n" on its own, and it counts as a line too. Maybe that's not what you want.

Good: skip lines with nothing on them

PYTHONedit me
f = open("story.txt", "w")
f.write("Sunny has a cat\n\nRocky has a dog\n")
f.close()

lines = 0
f = open("story.txt")
for line in f:
    if line.strip() != "":
        lines += 1
f.close()
print("Lines:", lines)
OUTPUT
Lines: 2

After strip(), an empty line becomes "", so the if skips it.

Common beginner doubt: "Can't I count with read() too?" Yes: len(text.split()) counts every word in the whole text at once. The loop is handy when you count several things in one go, as above.

Make the counters before the loop, then add to them for every line.

your turnType the output

Type what this prints

f = open("talk.txt", "w") f.write("hi there\nhow are you\n") f.close() words = 0 f = open("talk.txt") for line in f: words += len(line.split()) f.close() print(words)
Read the code line by line, then type the output exactly.
your turnPredict the output

Remember split() and join()?

words = "red green blue".split() print("-".join(words))
Your turn! What will this code show on the screen?

Practice: Read

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 174.Python Program to Read a File Line by LineEasySolve
  2. 175.Python Program to Count Lines and Words in a FileMediumSolve
  3. 176.Python Program to Find a Word in a FileMediumSolve