Skip to content

File Operations

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.

# 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 file
with 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 overwriting
with open("notes.txt", "a") as f:
f.write("Appended line\n")

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-write
f = open("notes.txt", "w")
f.write("data")
f.close()
# Safe -- closes automatically, even on error
with open("notes.txt", "w") as f:
f.write("data")
  1. Why is with open(...) as f: preferred over calling open() and close() manually?

    AnswerIt guarantees the file is closed even if an exception is raised inside the block β€” manual close() calls get skipped if an error happens first.
  2. What file mode do you use to add content without erasing what’s already there?

    Answer"a" (append mode).
  3. Why is iterating for line in f: often better than f.read() for large files?

    Answerf.read() loads the entire file into memory at once; iterating line by line reads incrementally, using far less memory for large files.