How to read and write files in Python
open function, read modes, write modes, with statement, read, readline, readlines, write, writelines, file encoding
Reading and Writing Files
Python's built-in open() returns a file object. Always use the with statement — it closes the file automatically even if an exception occurs.
# Writing a file
with open("data.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"])
# Reading the whole file
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read() # entire file as string
# Reading line by line (memory-efficient)
with open("data.txt", "r", encoding="utf-8") as f:
for line in f: # file object is iterable
print(line.strip())
File Modes
Common modes: "r" read (default), "w" write (truncates), "a" append, "x" exclusive create (fails if exists), "b" binary suffix. Always specify encoding="utf-8" explicitly to avoid platform-dependent defaults causing silent data corruption on Windows.
with open("data.txt", "a", encoding="utf-8") as f:
f.write("Line 5\n") # appends without truncating
File I/O is a frequent source of bugs when error handling is overlooked. A file might not exist, might lack read permissions, or the disk might be full during a write. Wrapping file operations in try/except blocks handles these gracefully. The pathlib.Path module is the modern Pythonic way to handle file paths — it is cross-platform and object-oriented, so you can write Path("dir") / "file.txt" instead of os.path.join. Avoid hardcoding paths; accept them as parameters or read from configuration so your code works across different environments.
