BrightPath
Back to Course
Year 10 Coding

File Handling in Python

Learn to read from and write to files using open(), read(), write(), and the with statement for safe file handling.

Opening and Reading Files

Programs often need to read data from files -- such as student records, configuration settings, or text documents. Python's open() function creates a connection to a file. You specify the filename and a mode ("r" for read, "w" for write, "a" for append).

# Reading an entire file
file = open("scores.txt", "r")
content = file.read()
print(content)
file.close()          # Always close the file when done!

# Reading line by line
file = open("scores.txt", "r")
for line in file:
    print(line.strip())   # strip() removes the newline character
file.close()

# Reading all lines into a list
file = open("scores.txt", "r")
lines = file.readlines()  # Returns a list of strings
print(lines)
file.close()

After opening a file, you must close it with .close() to free system resources. Forgetting to close files can cause data loss or bugs. There is a better way -- the with statement.

The with Statement (Best Practice)

The with statement is the recommended way to work with files in Python. It automatically closes the file when the block ends -- even if an error occurs.

# Reading with the 'with' statement -- file closes automatically
with open("scores.txt", "r") as file:
    content = file.read()
    print(content)
# No need to call file.close() -- it happens automatically!

# Reading line by line with 'with'
with open("students.txt", "r") as file:
    for line in file:
        name, score = line.strip().split(",")
        print(f"{name} scored {score}%")

Always prefer with open(...) as file: over manually opening and closing. It is cleaner, safer, and more Pythonic.

Writing and Appending to Files

Use mode "w" to write (overwrites existing content) or "a" to append (adds to the end). If the file does not exist, both modes create it.

# Writing to a file (creates or overwrites)
with open("output.txt", "w") as file:
    file.write("Name,Score\n")
    file.write("Ava,92\n")
    file.write("Ben,85\n")

# Appending to a file (adds to end)
with open("output.txt", "a") as file:
    file.write("Chloe,97\n")

# Writing multiple lines at once
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("multi.txt", "w") as file:
    file.writelines(lines)

Warning: "w" Mode Overwrites!

Opening a file with "w" mode will erase all existing content. Use "a" (append) if you want to add data without losing what is already there.

Key Vocabulary

File Mode

A string that tells Python how to open a file: "r" (read), "w" (write), "a" (append).

with Statement

A Python construct that automatically closes a file when the block ends, preventing resource leaks.

read()

A method that reads the entire contents of a file as a single string.

write()

A method that writes a string to a file. Does not automatically add a newline character.

Worked Examples

1

Read a file and count how many lines it contains.

with open("data.txt", "r") as file:
    lines = file.readlines()
    count = len(lines)

print(f"The file has {count} lines.")

Step 1: Open the file in read mode using with.

Step 2: Use .readlines() to get a list where each element is one line.

Step 3: Use len() to count the number of lines.

2

Write a list of student names to a file, one per line.

students = ["Ava", "Ben", "Chloe", "Dan"]

with open("students.txt", "w") as file:
    for name in students:
        file.write(name + "\n")

print("File written successfully!")

Step 1: Open the file in write mode ("w").

Step 2: Loop through the list and write each name followed by \n (newline).

Step 3: The file is automatically closed when the with block ends.

3

Read a CSV file and calculate the average score.

# File contents: Ava,92 / Ben,85 / Chloe,97
total = 0
count = 0

with open("scores.csv", "r") as file:
    for line in file:
        name, score = line.strip().split(",")
        total += int(score)
        count += 1

average = total / count
print(f"Average score: {average:.1f}%")
# Output: Average score: 91.3%

Step 1: Read each line and use .strip().split(",") to extract name and score.

Step 2: Convert the score to an integer and accumulate the total.

Step 3: After the loop, divide the total by count to get the average.

Knowledge Check

Select the correct answer for each question. Click "Check Answer" to see if you are right.

Question 1

Which file mode would you use to read an existing file?

Question 2

What is the main advantage of using the with statement for file handling?

Question 3

What happens if you open an existing file in "w" mode?

Question 4

Which method reads all lines of a file into a list?

Question 5

What mode should you use to add new data to the end of an existing file without erasing its current content?

Key Concepts Summary

Year 10: Dictionaries Year 10: Problem Solving