Lesson 10: File Handling (read/write)

How Python reads, writes, and manages files on your system

Why File Handling Matters

Many programs need to store or retrieve data from files. Python makes file handling simple and powerful with built‑in functions.

Opening a File

Use the open() function to work with files:

file = open("example.txt", "r")   # r = read mode

Common File Modes

Reading Files

Read the entire file:

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

Read line by line:

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

Read into a list:

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

Writing to Files

Write text to a file (overwrites existing content):

with open("output.txt", "w") as file:
    file.write("Hello, file!")

Appending to Files

Add new content without deleting existing data:

with open("output.txt", "a") as file:
    file.write("\nAnother line.")

Using the with Statement

The with keyword automatically closes the file when done. This is the recommended way to handle files.

Working with Paths

Use the os module to work with file paths:

import os

print(os.getcwd())          # current directory
print(os.path.exists("data.txt"))

Handling Exceptions

File operations often require error handling:

try:
    with open("missing.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("File not found!")

Next Steps

Now that you can read and write files, you're ready to learn how Python handles errors more broadly in Lesson 11: Error Handling with try/except.

← Back to Lesson Index