File I/O
Checking access...
Opening and Closing Files
# Basic open/closefile = open("data.txt", "r")content = file.read()file.close()
# Context manager — auto-closes even on errorswith open("data.txt", "r") as file: content = file.read()File Modes
# Modes:# "r" — read (default)# "w" — write (overwrites existing)# "a" — append# "x" — exclusive creation (fails if exists)# "b" — binary mode# "t" — text mode (default)# "+" — read and write
with open("notes.txt", "w") as f: f.write("New content") # Overwrites
with open("notes.txt", "a") as f: f.write("\nMore content") # Appends
with open("new_file.txt", "x") as f: f.write("Created") # Fails if existsReading Files
with open("data.txt", "r") as f: # All at once content = f.read() # Entire file as string
# Line by line for line in f: # Memory efficient for large files print(line.strip())
# All lines lines = f.readlines() # List of strings lines = f.read().splitlines() # Without trailing newlines
# Read specific amount chunk = f.read(1024) # First 1024 bytesWriting Files
# Text fileswith open("output.txt", "w", encoding="utf-8") as f: f.write("Line 1\n") f.write("Line 2\n") f.writelines(["Line 3\n", "Line 4\n"])
# Appendingwith open("log.txt", "a") as f: print("Error occurred", file=f) # print() can write to filesWorking with File Paths
# Old way — string concatenation (brittle)path = "/home/user/data/" + filename
# Better — pathlib (Python 3.4+)from pathlib import Path
data_dir = Path("/home/user/data")file_path = data_dir / "results.csv" # Uses / operator
# Common operationsp = Path("data/config.json")
p.exists() # True/Falsep.is_file() # True/Falsep.is_dir() # True/Falsep.name # 'config.json'p.stem # 'config'p.suffix # '.json'p.parent # Path('data')p.absolute() # Full path
# Reading/writing with pathlibp.write_text('{"key": "value"}')content = p.read_text()
# Directory operationsfor item in Path(".").iterdir(): print(item.name)
for py_file in Path("src").glob("**/*.py"): print(py_file)
# Create directoriesPath("output/data").mkdir(parents=True, exist_ok=True)Binary Files
# Reading binarywith open("image.jpg", "rb") as f: data = f.read() print(f"Read {len(data)} bytes")
# Writing binarywith open("output.bin", "wb") as f: f.write(b"\x00\x01\x02\x03")
# Copying binarywith open("source.jpg", "rb") as src, open("copy.jpg", "wb") as dst: dst.write(src.read())Temporary Files
from tempfile import TemporaryFile, NamedTemporaryFile, TemporaryDirectory
# Temporary file (no name, auto-deleted)with TemporaryFile("w+") as f: f.write("Temporary data") f.seek(0) print(f.read())
# Named temporary filewith NamedTemporaryFile(delete=True) as f: print(f"Temp file: {f.name}") f.write(b"data")
# Temporary directorywith TemporaryDirectory() as tmpdir: path = Path(tmpdir) / "work.txt" path.write_text("Working here")Structured Data Files
CSV
import csv
# Readingwith open("data.csv", "r") as f: reader = csv.DictReader(f) for row in reader: print(row["name"], row["age"])
# Writingwith open("output.csv", "w", newline="") as f: writer = csv.DictWriter(f, fieldnames=["name", "age"]) writer.writeheader() writer.writerow({"name": "Alice", "age": 30})JSON
import json
data = {"users": [{"name": "Alice", "age": 30}]}
# Writingwith open("data.json", "w") as f: json.dump(data, f, indent=2)
# Readingwith open("data.json", "r") as f: loaded = json.load(f)
# String conversionsjson_str = json.dumps(data)parsed = json.loads(json_str)File and Directory Operations
import shutilimport os
# Copyshutil.copy("source.txt", "dest.txt") # Fileshutil.copytree("src_dir", "dest_dir") # Directory
# Move/Renameshutil.move("old.txt", "new.txt")
# Deleteos.remove("file.txt") # Fileos.rmdir("empty_dir") # Empty directoryshutil.rmtree("dir_to_delete") # Directory + contents
# File infoos.path.getsize("data.txt") # Size in bytesos.path.getmtime("data.txt") # Last modified timestampKey Takeaways
- Always use
withfor file operations — auto-closes on errors - Modes:
rread,wwrite (overwrite),aappend,bbinary,+read+write - Use
pathlib.Pathfor path manipulation over string concatenation - CSV and JSON have dedicated modules in the standard library
shutilhandles file/directory copy, move, deletetempfilecreates temporary files and directories- Specify
encoding="utf-8"for text files to avoid platform issues