Open, read, write, and append to files using Python built-in functions.
Python makes file I/O simple with the built-in open() function. Always use the with statement — it automatically closes the file.
File Modes
r — read (default)
w — write (overwrites file)
a — append
x — create (fails if exists)
b — binary mode (e.g., rb, wb)
Reading Large Files
For large files, iterate line by line instead of reading all at once — saves memory.
Example
# Reading a file
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read() # Read entire file
# OR:
lines = f.readlines() # List of lines
# OR:
for line in f: # Memory-efficient line by line
print(line.strip())
# Writing a file (overwrites)
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!
')
f.writelines(['line 1
', 'line 2
'])
# Appending to a file
with open('log.txt', 'a') as f:
f.write('New log entry
')
# Working with JSON
import json
with open('data.json', 'w') as f:
json.dump({'name': 'Alice', 'age': 30}, f, indent=2)