Course Progress46%
🍎 Python Basics Topic 46 / 100
⏳ 7 min read

Reading Files

Open and read text files in Python — the gateway to working with real-world data that lives outside your program.

"Files let your program remember things after it finishes running. Reading a file is as simple as: open it, read it, close it."

— ShurAI

The open() Function

Python uses the built-in open() function to access files. Always use the with keyword — it automatically closes the file when you are done, even if an error occurs:

python — the pattern
with open("filename.txt", "r") as file:
    # do something with file
    content = file.read()

# file is automatically closed here
📄 File modes — second argument to open()
"r"
Read — default. File must exist.
"w"
Write — creates or overwrites the file.
"a"
Append — adds to the end, never overwrites.
"r+"
Read and write.

Read All at Once

Imagine notes.txt contains three lines: Python is great, Files are easy, Keep learning

python
# read() — returns the entire file as one big string
with open("notes.txt", "r") as f:
    content = f.read()

print(content)
# Python is great
# Files are easy
# Keep learning

print(type(content))    # <class 'str'>
print(len(content))     # total number of characters

Read Line by Line

python
# readlines() — returns a list, one string per line
with open("notes.txt", "r") as f:
    lines = f.readlines()

print(lines)
# ['Python is great\n', 'Files are easy\n', 'Keep learning']

# Loop directly — most memory-efficient (best for large files)
with open("notes.txt", "r") as f:
    for line in f:
        print(line.strip())   # .strip() removes the \n newline
Why .strip()?

Each line from a file includes a \n newline character at the end. Calling .strip() removes it so you get clean text. Without it, you get a blank line printed after every line.

Read a Specific Line

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

print(lines[0].strip())   # First line:  Python is great
print(lines[-1].strip())  # Last line:   Keep learning
print(len(lines))         # Total lines: 3

Handle Missing Files Gracefully

python
import os

filename = "data.txt"

if os.path.exists(filename):
    with open(filename, "r") as f:
        print(f.read())
else:
    print(f"File not found: {filename}")

Real Example — Word Counter

python
def analyse_file(filename):
    """Count lines, words and characters in a text file."""
    with open(filename, "r") as f:
        content = f.read()

    lines = content.splitlines()
    words = content.split()
    chars = len(content)

    print(f"File  : {filename}")
    print(f"Lines : {len(lines)}")
    print(f"Words : {len(words)}")
    print(f"Chars : {chars}")

analyse_file("notes.txt")

"Always use with open() — not just open(). The with block guarantees the file is properly closed, even if your code crashes halfway through."

— ShurAI

🧠 Quiz — Q1

What is the main benefit of using with open() instead of just open()?

🧠 Quiz — Q2

What does f.read() return?

🧠 Quiz — Q3

Why call .strip() on each line read from a file?

🧠 Quiz — Q4

What does f.readlines() return?