Introduction
Python provides built-in functions for reading from and writing to files.
Reading Files
# Read entire file
with open("file.txt", "r") as f:
content = f.read()
# Read line by line
with open("file.txt", "r") as f:
for line in f:
print(line.strip())
# Read all lines as list
with open("file.txt", "r") as f:
lines = f.readlines()
Writing Files
# Write (overwrites)
with open("output.txt", "w") as f:
f.write("Hello, World!")
# Append
with open("log.txt", "a") as f:
f.write("\nNew entry")
# Write multiple lines
lines = ["line1", "line2", "line3"]
with open("output.txt", "w") as f:
f.write("\n".join(lines))
Working with CSV
import csv
# Reading CSV
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# Writing CSV
data = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]
with open("output.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
Practice Problems
- Copy contents of one file to another
- Count lines, words, and characters in a file
- Search for pattern in file
- Read and parse CSV data
- Implement a simple text file editor