File Operations
File Operations
Section titled βFile OperationsβWhat it means
Section titled βWhat it meansβPython reads and writes files through file objects, typically opened with open(). The recommended pattern is the with statement (a context manager), which automatically closes the file even if an error occurs partway through β you should almost never call .close() manually.
Examples
Section titled βExamplesβ# Writing to a file (overwrites if it exists)with open("notes.txt", "w") as f: f.write("Hello, file!\n") f.write("Second line\n")
# Reading an entire filewith open("notes.txt", "r") as f: contents = f.read()
# Reading line by line (memory-efficient for large files)with open("notes.txt", "r") as f: for line in f: print(line.strip())
# Appending instead of overwritingwith open("notes.txt", "a") as f: f.write("Appended line\n")Common mistake
Section titled βCommon mistakeβOpening a file without with and forgetting to close it β this can leak file handles and, for writes, means data may not be flushed to disk if the program crashes or exits early.
# Risky -- file may never get closed if an exception happens mid-writef = open("notes.txt", "w")f.write("data")f.close()
# Safe -- closes automatically, even on errorwith open("notes.txt", "w") as f: f.write("data")Quick practice
Section titled βQuick practiceβ-
Why is
with open(...) as f:preferred over callingopen()andclose()manually?Answer
It guarantees the file is closed even if an exception is raised inside the block β manualclose()calls get skipped if an error happens first. -
What file mode do you use to add content without erasing whatβs already there?
Answer
"a"(append mode). -
Why is iterating
for line in f:often better thanf.read()for large files?Answer
f.read()loads the entire file into memory at once; iterating line by line reads incrementally, using far less memory for large files.