How do I read from and write to files in Python?
· Category: Python Programming
Short answer
Use the built-in open() function to open a file and a with statement to ensure it closes automatically. Specify the mode (r, w, a, b) and encoding as needed.
Steps
- Open the file with a context manager.
- Read or write inside the indented block.
- The file closes automatically when the block ends.
# Reading
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
# or line by line
for line in f:
print(line.strip())
# Writing
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!
")
f.writelines(["Line 1
", "Line 2
"])
Tips
- Always specify
encoding="utf-8"to avoid platform-dependent defaults. - Use
readlines()or iterate over the file object for memory-efficient reading of large files. - Append mode (
a) adds to the end without truncating existing content. - Binary mode (
rb,wb) is required for non-text files like images.
Common issues
- Forgetting to close a file leaks file descriptors; always use
with. - Reading after the file has been closed raises a
ValueError. - Writing to a file opened in read mode raises an
UnsupportedOperation.