Introduction
Working with files is essential for any real-world application. Python makes file operations straightforward with the built-in open() function and context managers.
Reading and writing files
# Writing to a file
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.write("Second line.\n")
# Reading a file
with open("output.txt", "r") as f:
content = f.read() # entire file as string
with open("output.txt", "r") as f:
lines = f.readlines() # list of lines
with open("output.txt", "r") as f:
for line in f: # iterate line by line (memory efficient)
print(line.strip())
# Working with JSON
import json
data = {"name": "Alice", "scores": [95, 87, 92]}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
with open("data.json", "r") as f:
loaded = json.load(f)
# Working with CSV
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 30])Assignment
- Write a program that reads a text file and counts the frequency of each word.
- Create a simple contact book that saves and loads data from a JSON file.