Skip to the content

Reading a file

Python · Unit 17: Files

open(name) with no mode opens the file for reading, and read() returns the whole file as a single text.

with is the right habit for reading too. The line print(open(...).read()) is just the shortcut for a quick peek.

with open("today.txt", "w") as f:
    f.write("bread\nmilk\n")
with open("today.txt") as f:
    text = f.read()
print(text)
print(len(text))

Prints

bread
milk

11

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Complete it to show the whole file as a single text.

  3. 3. Predict the output

    What does this code print?

  4. 4. Complete the code

    Complete it to show each name without the line break.

  5. 5. Put the lines in order

    Put the lines in order to save two colors and show the list of lines.

  6. 6. Predict the output

    What does this code print?

  7. 7. Find the case that fails

    first(text) saves text in a file and should return its first line, or "" if the file ended up empty. Which call breaks it?

  8. 8. Find the bug

    This program should show what was saved. Which line has the bug?

  9. 9. Predict the output

    What does this code print?

  10. 10. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →