🐍 Python 2026 › Lesson 14: File Input and Output
Lesson 14 of 30

File Input and Output

Reading and writing text files, CSV files, and using the with statement.

Writing to a File

Use the built-in open() function with the with statement, which automatically closes the file:

with open("notes.txt", "w") as f:
    f.write("Hello from Python!\n")
    f.write("Line two\n")

Reading from a File

with open("notes.txt", "r") as f:
    content = f.read()           # entire file as string
    print(content)

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

File Modes

ModeMeaning
rRead (default)
wWrite (overwrites)
aAppend
xCreate (fails if exists)
bBinary mode (combine: rb, wb)

Working with CSV Files

import csv

# Write CSV
with open("students.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Score"])
    writer.writerow(["Alice", 95])
    writer.writerow(["Bob", 82])

# Read CSV
with open("students.csv", "r") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["Name"], row["Score"])