Python · files

File Reading

Open a text file, read it all at once, line by line or a few characters at a time, and close it again.

The file we will read


          First line
          Second line
          Third line
        

data.txt

Three lines. Each ends with a newline character \n, drawn as ↵ in the pictures.

The cursor

An open file remembers where it is. Every read starts at the cursor and moves it forward.

Open and read


          # open and read file
          file = open("data.txt", "r")
          content = file.read()
          file.close()
        

Context manager (best practice)


          # with statement
          with open("data.txt", "r") as file:
              content = file.read()
          # ans: file automatically closed
        

The file closes when the indented block ends, even if an error happens inside it.

Read lines


          # read all lines
          with open("data.txt", "r") as file:
              lines = file.readlines()
          # ans: returns list of lines
        

Read line by line


          # iterate over lines
          with open("data.txt", "r") as file:
              for line in file:
                  print(line.strip())
        

Only one line is in memory at a time, so this works for files of any size.

The readline method


          # read one line at a time
          with open("data.txt", "r") as file:
              line1 = file.readline()
              line2 = file.readline()
        

Read with a limit


          # read n characters
          with open("data.txt", "r") as file:
              content = file.read(10)
          # ans: first 10 characters
        

Exercises

Predict, then reveal. Watch the cursor.

Exercise 1


          # what happens without close?
          file = open("data.txt", "r")
          content = file.read()
          # ans: file remains open (bad practice)
        

Exercise 2


          # read() returns what type?
          with open("data.txt", "r") as f:
              content = f.read()
          # ans: str (string)
        

Exercise 3


          # readlines() returns?
          with open("data.txt", "r") as f:
              lines = f.readlines()
          # ans: list of strings
        

Exercise 4


          # strip() in loop?
          for line in file:
              print(line.strip())
          # ans: removes \n at end
        

Exercise 5


          # read empty file?
          with open("empty.txt", "r") as f:
              content = f.read()
          # ans: "" (empty string)
        

Exercise 6


          # file not found?
          with open("missing.txt", "r") as f:
              pass
          # ans: FileNotFoundError
        

Exercise 7


          # read twice?
          with open("data.txt", "r") as f:
              c1 = f.read()
              c2 = f.read()
          # ans: c2 is "" (already at end)
        

Exercise 8


          # readline at end?
          with open("data.txt", "r") as f:
              f.read()
              line = f.readline()
          # ans: "" (empty string)
        

Exercise 9


          # iterate multiple times?
          with open("data.txt", "r") as f:
              for line in f:
                  pass
              for line in f:
                  pass
          # ans: second loop doesn't run
        

Call f.seek(0) to move the cursor back to the start before reading again.

Exercise 10


          # read with encoding?
          with open("data.txt", "r", encoding="utf-8") as f:
              content = f.read()
          # ans: specify encoding explicitly
        

Without it, Python uses the system's default encoding, which differs between computers.

Remember

with open(...)

Closes the file for you. Without it, call close() yourself.

Pick a read

read() one string, read(n) n characters, readline() one line, readlines() a list.

Loop for big files

for line in file reads one line at a time; strip() removes the \n.

The cursor moves

At the end, reads return "" and loops do nothing, until you seek(0).