with open("config.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content[:50])
# Read line by line (memory efficient)with open("data.log") as f:
for line in f:
print(line.strip())
Note Always specify encoding='utf-8' explicitly. The default varies by platform. Iterating line-by-line avoids loading the entire file into memory.
read fileopen fileload textfile contents
Writing Files
syntax
with open(path, 'w') as f:
f.write(text)
example
lines = ["alice,95", "bob,82", "carol,91"]
with open("scores.csv", "w", encoding="utf-8") as f:
f.write("name,score\n")
for line in lines:
f.write(line + "\n")
# Append modewith open("scores.csv", "a") as f:
f.write("dave,88\n")
Note 'w' mode truncates the file first. Use 'a' to append. Use 'x' to create exclusively (fails if file exists).
import csv
# Writingwith open("users.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age"])
writer.writeheader()
writer.writerow({"name": "Alice", "age": 30})
writer.writerow({"name": "Bob", "age": 25})
# Readingwith open("users.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], row["age"])
output
Alice 30
Bob 25
Note Always pass newline='' when opening CSV files (the csv module handles line endings itself). DictReader/DictWriter are more readable than plain reader/writer.
Note json.dump/load work with file objects. json.dumps/loads work with strings. Use indent= for readable output. Python dicts serialize directly to JSON objects.
# Copy a binary filewith open("image.png", "rb") as src:
data = src.read()
with open("copy.png", "wb") as dst:
dst.write(data)
print(f"Copied {len(data)} bytes")
Note Use 'rb' / 'wb' modes for binary files (images, archives, etc.). Never open binary files in text mode; it corrupts the data on some platforms.
from contextlib import contextmanager
@contextmanager
def temp_directory():
import tempfile, shutil
path = tempfile.mkdtemp()
try:
yield path
finally:
shutil.rmtree(path)
with temp_directory() as tmp:
print(f"Working in {tmp}")
Note The with statement guarantees cleanup code runs even if an exception occurs. Use contextlib.contextmanager to build custom context managers from generators.
from pathlib import Path
# All Python files in current directoryfor py_file in Path(".").glob("*.py"):
print(py_file.name)
# Recursive search
all_json = list(Path(".").rglob("*.json"))
print(f"Found {len(all_json)} JSON files")
Note glob() searches one level. rglob() searches recursively through all subdirectories. Both return Path objects.