File I/O

File I/O (input/output) lets you read data from files and write data to files.

Reading a File

Use open() with "r" for reading, and always use with to automatically close the file:

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

Reading Line by Line

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

Note: .strip() removes the newline character at the end of each line.

Reading All Lines into a List

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

print(lines)

Output (if file contains "Alice", "Bob", "Carol" on separate lines):

['Alice\n', 'Bob\n', 'Carol\n']

A cleaner version using a loop:

with open("names.txt", "r") as file:
    names = []
    for line in file:
        names.append(line.strip())

print(names)

Output:

['Alice', 'Bob', 'Carol']

Writing to a File

Use "w" mode to write. This creates a new file or overwrites an existing one:

with open("output.txt", "w") as file:
    file.write("Hello!\n")
    file.write("This is line 2.\n")

Appending to a File

Use "a" mode to add to the end of a file without erasing it:

with open("log.txt", "a") as file:
    file.write("New entry\n")

File Paths

# Same folder as your script
with open("data.txt", "r") as file:
    content = file.read()

# In a subfolder
with open("data/records.txt", "r") as file:
    content = file.read()

Tip: Use relative paths (like "data/file.txt") so your code works on different computers.

Working with CSV Files

CSV (comma-separated values) files store table-like data:

name,age,major
Alice,20,CS
Bob,21,Math

Reading CSV Manually

with open("students.csv", "r") as file:
    for line in file:
        values = line.strip().split(",")
        print(values)

Output:

['name', 'age', 'major']
['Alice', '20', 'CS']
['Bob', '21', 'Math']

Using the csv Module

import csv

with open("students.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["name"] + " is " + row["age"])

Output:

Alice is 20
Bob is 21

Writing CSV Files

import csv

students = [
    ["Alice", "20", "CS"],
    ["Bob", "21", "Math"]
]

with open("output.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["name", "age", "major"])  # header
    writer.writerows(students)                  # data

Handling Missing Files

import os

if os.path.exists("data.txt"):
    with open("data.txt", "r") as file:
        content = file.read()
else:
    print("File not found!")

Or use try/except:

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

Common Mistakes

Forgetting to use with

# Wrong - file might not close properly
file = open("data.txt", "r")
content = file.read()
file.close()

# Right - file closes automatically
with open("data.txt", "r") as file:
    content = file.read()

Using the wrong mode

# Wrong - "r" mode can't write
with open("output.txt", "r") as file:
    file.write("Hello")  # Error!

# Right - use "w" to write
with open("output.txt", "w") as file:
    file.write("Hello")

Forgetting newlines when writing

# Wrong - all on one line
with open("names.txt", "w") as file:
    file.write("Alice")
    file.write("Bob")
# File contains: AliceBob

# Right - add \n for new lines
with open("names.txt", "w") as file:
    file.write("Alice\n")
    file.write("Bob\n")

Not stripping newlines when reading

# Wrong - names have \n attached
with open("names.txt", "r") as file:
    for line in file:
        print("Hello " + line + "!")
# Output: Hello Alice
#         !

# Right - strip the newline
with open("names.txt", "r") as file:
    for line in file:
        print("Hello " + line.strip() + "!")
# Output: Hello Alice!