
Reading a file:
with open("file.txt", "r") as f:
content = f.read() # entire file as string
with open("file.txt", "r") as f:
lines = f.readlines() # list of lines
with open("file.txt", "r") as f:
for line in f: # line by line (memory efficient)
print(line.strip())Writing a file:
with open("output.txt", "w") as f: # overwrites
f.write("Hello\n")
f.write("World\n")
with open("output.txt", "a") as f: # appends
f.write("New line\n")File modes:
"r" — read, "w" — write (overwrite), "a" — append, "rb" — read binary, "wb" — write binary
Always use with: It automatically closes the file even if an error occurs. Never use f = open() without a with block in production code.
Reference:
TaskLoco™ — The Sticky Note GOAT