← Back to Blog

File Handling — The Full Picture

You've covered file handling from every angle. Before moving on, here's everything in one place.

// The pattern — always

with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()
# file closed automatically

// Modes

"r"    # read — file must exist
"w"    # write — creates or overwrites
"a"    # append — adds to end, preserves existing

// Reading

f.read()              # whole file as string
f.readlines()         # all lines as list (with \n)
f.readline()          # one line at a time
for line in f:        # line by line — most common
    line.strip()      # removes \n and whitespace

// Writing

f.write(string)       # write one string — add \n manually
f.writelines(list)    # write list of strings — add \n in strings

// CSV — reading

import csv

with open("file.csv", "r", encoding="utf-8") as f:
    reader = csv.reader(f)
    next(reader)            # skip header
    for row in reader:
        print(row)          # row is a list of strings

with open("file.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["key"])   # row is a dict

// CSV — writing

with open("file.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "score"])  # one row
    writer.writerows(rows)              # multiple rows

with open("file.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "score"])
    writer.writeheader()
    writer.writerows(dicts)

// Error handling

try:
    with open("file.txt", "r", encoding="utf-8") as f:
        content = f.read()
except FileNotFoundError:
    print("File not found.")

// Common mistakes

# forget with open()     → file stays locked
# "w" mode              → silent overwrite, no undo
# missing \n            → everything on one line
# CSV values            → all strings — convert with int(), float()
# missing newline=""    → blank lines between CSV rows on Windows
# read() twice          → second read returns "" — store in variable

That's file handling. Your data now survives the program.

The cheatsheet above is yours to download and keep.

[ login to bookmark ] // copied! 18 views · 1 min
// resources
Cheatsheet File Handling — The Full Picture
← prev Common File Handling Mistakes next → The Foundation Is Set
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.