BrightPath
Back to Course
Year 11 Coding

Python File I/O

Learn to read from and write to files, use the with statement for safe file handling, and process CSV data.

Reading and Writing Files

Python can read from and write to files on your computer. The open() function creates a file object. The most common modes are "r" (read), "w" (write), and "a" (append).

# Writing to a file
with open("greeting.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("Welcome to Python file I/O.\n")
    file.write("This is line 3.\n")

# Reading the entire file
with open("greeting.txt", "r") as file:
    content = file.read()
    print(content)

# Reading line by line
with open("greeting.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip() removes the \n
"w" creates/overwrites the file  |  "a" adds to the end  |  "r" reads only

The with Statement

The with statement is the recommended way to work with files. It automatically closes the file when the block ends, even if an error occurs. This prevents data loss and resource leaks.

# WITHOUT with (not recommended)
file = open("data.txt", "r")
content = file.read()
file.close()        # You must remember to close!

# WITH with (recommended - auto-closes)
with open("data.txt", "r") as file:
    content = file.read()
# File is automatically closed here

# Appending to a file
with open("log.txt", "a") as file:
    file.write("New log entry added.\n")
Always use with when working with files. It ensures the file is properly closed.

Processing CSV Files

CSV (Comma-Separated Values) files are a common way to store tabular data. Python's built-in csv module makes reading and writing CSV files simple.

import csv

# Writing a CSV file
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "Score"])  # Header
    writer.writerow(["Alice", 16, 92])
    writer.writerow(["Bob", 17, 85])
    writer.writerow(["Charlie", 16, 78])

# Reading a CSV file
with open("students.csv", "r") as file:
    reader = csv.reader(file)
    header = next(reader)  # Skip header row
    print(f"Columns: {header}")
    for row in reader:
        name, age, score = row
        print(f"{name} (age {age}): {score}%")

Key Vocabulary

File I/O

Input/Output operations for reading data from and writing data to files on disk.

File Mode

How the file is opened: "r" read, "w" write, "a" append.

CSV

Comma-Separated Values: a text format for storing tabular data where each field is separated by a comma.

Context Manager

The with statement that automatically handles resource cleanup (e.g., closing files).

Worked Examples

1

Save and load a to-do list

# Save tasks to a file
tasks = ["Buy groceries", "Finish homework", "Clean room"]

with open("todo.txt", "w") as file:
    for task in tasks:
        file.write(task + "\n")
print("Tasks saved!")

# Load tasks from the file
with open("todo.txt", "r") as file:
    loaded_tasks = [line.strip() for line in file]

print(f"Loaded {len(loaded_tasks)} tasks:")
for i, task in enumerate(loaded_tasks, 1):
    print(f"  {i}. {task}")

Step 1: Write each task on a new line with \n.

Step 2: Read the file back and use .strip() to remove newline characters.

2

Count words in a text file

# First create a sample file
with open("sample.txt", "w") as file:
    file.write("Python is a great language.\n")
    file.write("It is easy to learn.\n")
    file.write("Python is used everywhere.\n")

# Count words, lines, and characters
with open("sample.txt", "r") as file:
    content = file.read()
    lines = content.strip().split("\n")
    words = content.split()
    chars = len(content)

print(f"Lines: {len(lines)}")
print(f"Words: {len(words)}")
print(f"Characters: {chars}")

Step 1: Read the entire content, then split by newlines for lines and by spaces for words.

Output: Lines: 3 | Words: 15 | Characters: 78

3

Read a CSV and calculate averages

import csv

# Read scores and calculate average per student
with open("students.csv", "r") as file:
    reader = csv.reader(file)
    next(reader)  # Skip header

    for row in reader:
        name = row[0]
        score = int(row[2])
        if score >= 50:
            status = "PASS"
        else:
            status = "FAIL"
        print(f"{name}: {score}% - {status}")

Step 1: Use csv.reader() and skip the header with next().

Step 2: Convert score to integer and determine pass/fail status.

Knowledge Check

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

Question 1

Which mode opens a file for reading only?

Question 2

What is the main advantage of using the with statement for files?

Question 3

What does the "a" mode do when opening a file?

Question 4

What does CSV stand for?

Question 5

What method reads the entire file content as a single string?

Key Concepts Summary

Previous: Python Dictionaries Next: Python Error Handling