Python Cheatsheet

Files

Use this Python reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Opening Files

# open(file, mode='r', encoding=None, errors='strict', buffering=-1, newline=None)
f = open("file.txt", "r")           # read text (default)
f = open("file.txt", "w")           # write text (truncates)
f = open("file.txt", "a")           # append text
f = open("file.txt", "x")           # exclusive create (fails if exists)
f = open("file.txt", "r+")          # read and write
f = open("file.txt", "rb")          # read binary
f = open("file.txt", "wb")          # write binary
f = open("file.txt", encoding="utf-8")  # explicit encoding

# Always use with (context manager) — auto-closes on exit
with open("file.txt") as f:
    content = f.read()

Mode Flags

ModeMeaning
"r"Read (default)
"w"Write (truncate)
"a"Append
"x"Exclusive create — fails if file exists
"b"Binary mode (combine with r/w/a)
"t"Text mode (default)
"+"Read+write (combine: "r+", "w+", "a+")

Reading Files

with open("file.txt") as f:
    content = f.read()           # entire file as string
    # or
    lines = f.readlines()        # list of lines (with \n)
    # or
    line = f.readline()          # one line at a time

# Iterate line by line (memory efficient — does not load all)
with open("file.txt") as f:
    for line in f:
        print(line.rstrip("\n"))

# Read with size limit
with open("file.txt") as f:
    chunk = f.read(1024)         # read up to 1024 chars

# Binary
with open("image.png", "rb") as f:
    data = f.read()              # bytes object

# Read all lines, stripped
with open("file.txt") as f:
    lines = [line.rstrip() for line in f]

Writing Files

with open("out.txt", "w") as f:
    f.write("Hello\n")           # returns number of chars written
    f.write("World\n")

# Write multiple lines
with open("out.txt", "w") as f:
    f.writelines(["line1\n", "line2\n", "line3\n"])
    # writelines does NOT add \n automatically

# print to file
with open("out.txt", "w") as f:
    print("Hello", file=f)       # adds \n automatically
    print("World", file=f)

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

# Binary write
with open("out.bin", "wb") as f:
    f.write(b"\x00\xff\x42")

# Write from bytes
with open("out.bin", "wb") as f:
    f.write(bytes([0, 255, 66]))

File Position

with open("file.txt", "r+") as f:
    f.seek(0)          # move to byte position 0 (start)
    f.seek(10)         # move to byte 10
    f.seek(0, 2)       # move to end (whence=2)
    f.seek(-5, 2)      # 5 bytes from end
    f.seek(5, 1)       # 5 bytes from current (whence=1)
    pos = f.tell()     # current position (bytes)
    f.read(5)
    f.truncate()       # truncate at current position
    f.truncate(100)    # truncate to 100 bytes

os and os.path

import os
import os.path

os.getcwd()                      # current working directory
os.chdir("/tmp")                 # change directory
os.listdir(".")                  # list directory
os.makedirs("a/b/c", exist_ok=True)  # create dirs recursively
os.remove("file.txt")            # delete file
os.rmdir("empty_dir")            # delete empty directory
os.rename("old.txt", "new.txt")  # rename/move
os.stat("file.txt")              # stat result (size, mtime, etc.)

# os.path (use pathlib instead in new code)
os.path.join("dir", "file.txt")  # "dir/file.txt"
os.path.exists("file.txt")
os.path.isfile("file.txt")
os.path.isdir("dir")
os.path.basename("/dir/file.txt")  # "file.txt"
os.path.dirname("/dir/file.txt")   # "/dir"
os.path.splitext("file.txt")       # ("file", ".txt")
os.path.abspath("rel.txt")
os.path.expanduser("~/docs")       # expands ~
os.path.getsize("file.txt")        # size in bytes

# Walk directory tree
for dirpath, dirnames, filenames in os.walk("."):
    for fn in filenames:
        print(os.path.join(dirpath, fn))

Temporary Files

import tempfile

# Context managers — auto-deleted on exit
with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=True) as f:
    f.write("temporary data")
    name = f.name     # accessible path while open

with tempfile.TemporaryDirectory() as tmpdir:
    p = Path(tmpdir) / "work.txt"
    p.write_text("data")
# dir and contents deleted here

# Standalone
tmp = tempfile.mkstemp(suffix=".txt")  # (fd, path) — you must delete
fd, path = tmp
os.close(fd)
# ... use path ...
os.remove(path)

tmpdir = tempfile.mkdtemp()
# ... use tmpdir ...
import shutil
shutil.rmtree(tmpdir)

shutil — High-Level File Operations

import shutil

shutil.copy("src.txt", "dst.txt")          # copy file (no metadata)
shutil.copy2("src.txt", "dst.txt")         # copy file + metadata
shutil.copyfile("src", "dst")              # copy content only (dst must not be dir)
shutil.move("src", "dst")                  # move/rename (across filesystems)
shutil.rmtree("dir")                       # delete directory tree
shutil.copytree("src_dir", "dst_dir")      # copy entire directory

# Archives
shutil.make_archive("archive", "zip", "dir")    # create zip
shutil.unpack_archive("archive.zip", "out_dir") # extract

# Disk usage
total, used, free = shutil.disk_usage("/")

CSV Files

import csv

# Read
with open("data.csv", newline="") as f:
    reader = csv.reader(f)
    header = next(reader)
    for row in reader:
        print(row)   # list of strings

# DictReader — rows as dicts
with open("data.csv", newline="") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])

# Write
with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "age"])    # header
    writer.writerows([["Alice", 30], ["Bob", 25]])

# DictWriter
with open("out.csv", "w", newline="") as f:
    fieldnames = ["name", "age"]
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({"name": "Alice", "age": 30})

JSON Files

import json

# Write
with open("data.json", "w") as f:
    json.dump(obj, f, indent=2)             # pretty-print
    json.dump(obj, f, indent=2, sort_keys=True)

# Read
with open("data.json") as f:
    obj = json.load(f)

# String ↔ object (no file)
s = json.dumps(obj, indent=2)   # to string
obj = json.loads(s)             # from string

# Custom serialization
class Encoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

json.dumps(obj, cls=Encoder)