Reading Files

Files

Reading Files

In this tutorial, we'll read whole files and process files line by line.

Reading a file means loading its contents into your program.

Use "r" mode:

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

print(content)

read() loads the whole file as one string.

Reading Lines

For larger files, you may want to read line by line:

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

Each line includes the newline character at the end. If you want to remove extra spacing, use .strip():

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

Reading Into a List

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

print(lines)

This gives you a list of lines.

Common Mistake

Reading a file that does not exist raises FileNotFoundError.

Check the filename and folder carefully. Most beginner file problems are path problems.

Processing File Data

Once you can read lines, you can process them:

with open("scores.txt", "r") as file:
    for line in file:
        score = int(line.strip())
        print(score * 2)

This reads each line, removes extra whitespace, converts it to an integer, and uses it.

Practice

Create a file with three lines. Read it line by line and print each line with its line number.