Opening & Reading Files
Exit

Opening & Reading Files

Use open(), with, .read(), and .readlines() to read text files

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Reading a file

Use open() with the "r" mode to read a file. Pair it with with so the file closes automatically.

with open("report.txt", "r") as file:
    content = file.read()
print(content)

Two ways to read

MethodReturnsUse when
file.read()One string with the full fileYou need all the text at once
file.readlines()A list — one string per lineYou need to process lines individually

Each line from readlines() includes the newline character \n at the end. Use .strip() to remove it.

with open("report.txt", "r") as file:
    lines = file.readlines()
print(lines[0].strip())  # First line without newline

Instructions

Read a sales report file using both .read() and .readlines().

  1. Open report.txt in read mode using with open("report.txt", "r") as file:. Inside the block, assign file.read() to content.
  2. Call print(content.strip()) to print all content without trailing whitespace.
  3. Open report.txt again using a second with statement. Inside the block, assign file.readlines() to lines.
  4. Call print(len(lines)) to print the number of lines.