IntermediateLesson firstCategory 14 of 20

Reading Files

Open and read data from files. Read the lesson first, then move through the exercises in order.

7 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Sequence Reading Logic

Study Material

Read the full lesson

Opening a file to read

The safest way is to use a with block. It closes the file for you.

python
with open("notes.txt", "r") as f: text = f.read()

Reading the whole file

read() returns one big string.

python
with open("notes.txt", "r") as f: text = f.read() print(text)

Reading line by line

You can loop over the file to get one line at a time.

python
with open("notes.txt", "r") as f: for line in f: print(line.strip())

strip() removes the newline at the end of each line.

Reading all lines at once

python
with open("notes.txt", "r") as f: lines = f.readlines()

File not found errors

If the path is wrong, Python raises FileNotFoundError. Check your folder and spelling.

Common mistakes to avoid

  • Forgetting to close the file (use with).
  • Printing lines without strip(), which adds extra blank lines.
  • Mixing reading and writing in the same open call.

What you should understand after this lesson

  • How to open a file safely for reading.
  • The difference between read(), readlines(), and looping.
  • How to handle missing files.

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.