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
| Method | Returns | Use when |
|---|---|---|
file.read() | One string with the full file | You need all the text at once |
file.readlines() | A list — one string per line | You 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().
- Open
report.txtin read mode usingwith open("report.txt", "r") as file:. Inside the block, assignfile.read()tocontent. - Call
print(content.strip())to print all content without trailing whitespace. - Open
report.txtagain using a secondwithstatement. Inside the block, assignfile.readlines()tolines. - Call
print(len(lines))to print the number of lines.
# report.txt contains: # Sales Report # Q1: 15000 # Q2: 18500 # Q3: 21000 # Step 1: Open report.txt and read its full content into content # Step 2: Print content using .strip() # Step 3: Open report.txt again and read it as lines # Step 4: Print the number of lines
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding