Lesson 95 +10 XP

Read Files

Read Files

After opening a file for reading, you pull its contents out in a few ways.

Read the whole file

f = open("demofile.txt", "r")
print(f.read())

Read part of a file

Pass a number to read only that many characters:

print(f.read(5))

Read one line

print(f.readline())

Each call reads the next line, so calling it twice reads two lines.

Loop through the file

for x in f:
    print(x)

The loop reads the file line by line, which is great for big files.

Close the file

f.close()

Missing file

Opening a missing file in "r" mode raises a FileNotFoundError:

try:
    f = open("nope.txt", "r")
except FileNotFoundError:
    print("No such file")

TL;DR

  • read() reads everything or N characters.
  • readline() reads one line at a time.
  • A for loop streams the file line by line.
  • Close the file when done.