Python 3 — File I/O Operations
File I/O (Input/Output) lets your program read data from files and write results back to disk. This is essential for saving data between program runs, reading configuration, processing CSV data, and logging. Python makes file handling intuitive with its open() function and with statement.
1 Opening & Reading Files
Python 3 — Reading Files▶ Run Code
# File modes:
# 'r' — Read (default) — error if file doesn't exist
# 'w' — Write — creates new or overwrites existing
# 'a' — Append — adds to end of file
# 'x' — Exclusive create — error if file exists
# 'b' — Binary mode (add to others: 'rb', 'wb')
# Reading entire file (with statement auto-closes file)
# Create a test file first:
with open("example.txt", "w") as f:
f.write("Hello, Python!\n")
f.write("File handling is easy.\n")
f.write("Line 3 here.\n")
# Now read it back
with open("example.txt", "r") as f:
content = f.read() # Read entire file as string
print(content)
# Read line by line
with open("example.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes newline chars
2 Reading Methods
Python 3 — Read Methods▶ Run Code
# Create a sample file
lines_data = ["Alice,92,A\n", "Bob,78,B\n", "Charlie,85,B+\n"]
with open("students.txt", "w") as f:
f.writelines(lines_data)
# .read() — entire file as one string
with open("students.txt") as f:
data = f.read()
print(repr(data))
# .readline() — one line at a time
with open("students.txt") as f:
first_line = f.readline()
second_line = f.readline()
print(first_line.strip())
print(second_line.strip())
# .readlines() — all lines as a list
with open("students.txt") as f:
all_lines = f.readlines()
print(all_lines)
print(f"Total lines: {len(all_lines)}")
3 Writing & Appending
Python 3 — Writing Files▶ Run Code
# Write mode ('w') — creates or OVERWRITES
with open("log.txt", "w") as f:
f.write("=== Application Log ===\n")
f.write("Session started\n")
for i in range(1, 4):
f.write(f"Event {i}: User action\n")
# Append mode ('a') — adds to existing file
with open("log.txt", "a") as f:
f.write("New event added\n")
f.write("Session ended\n")
# writelines() — write a list of strings
data = [f"Student {i}: Score {i*10}\n" for i in range(1, 6)]
with open("scores.txt", "w") as f:
f.writelines(data)
# Read back to verify
with open("log.txt") as f:
print(f.read())
4 Working with CSV Files
Python 3 — CSV Files▶ Run Code
import csv
# Writing CSV
students = [
["Name", "Age", "Score", "Grade"],
["Alice", 20, 92, "A"],
["Bob", 22, 78, "B"],
["Charlie", 21, 85, "B+"]
]
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(students)
# Reading CSV
with open("students.csv", "r") as f:
reader = csv.reader(f)
header = next(reader) # Skip header row
print(f"Columns: {header}")
for row in reader:
name, age, score, grade = row
print(f"{name}: Score {score} ({grade})")
# DictWriter — write with headers as keys
with open("data.csv", "w", newline="") as f:
fieldnames = ["product", "price", "quantity"]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({"product": "Laptop", "price": 999.99, "quantity": 5})
5 JSON Files
Python 3 — JSON Files▶ Run Code
import json
# Python dict to JSON file
config = {
"app_name": "Our Compiler",
"version": "2.0",
"languages": ["Python", "Java", "C++"],
"settings": {
"theme": "dark",
"font_size": 14
}
}
# Write JSON
with open("config.json", "w") as f:
json.dump(config, f, indent=2) # indent for pretty print
# Read JSON back into Python dict
with open("config.json", "r") as f:
loaded = json.load(f)
print(loaded["app_name"]) # Our Compiler
print(loaded["languages"]) # ['Python', 'Java', 'C++']
print(loaded["settings"]["theme"]) # dark
# Convert dict to JSON string
json_str = json.dumps(config, indent=2)
print(json_str[:100] + "...")
# Parse JSON string to dict
data = json.loads('{"name": "Balaji", "age": 25}')
print(data["name"]) # Balaji
6 File & Path Operations with os
Python 3 — os.path▶ Run Code
import os
# Check if file exists before reading
filename = "example.txt"
if os.path.exists(filename):
with open(filename) as f:
print(f.read())
else:
print(f"File '{filename}' not found!")
# File info
if os.path.exists(filename):
size = os.path.getsize(filename)
print(f"File size: {size} bytes")
# Create directory
os.makedirs("output/data", exist_ok=True) # Creates nested dirs
# List files with specific extension
for f in os.listdir("."):
if f.endswith(".txt"):
print(f"Found text file: {f}")
# Rename and delete
# os.rename("old.txt", "new.txt")
# os.remove("temp.txt")
7 Safe File Operations with try-except
Python 3 — Safe File Ops▶ Run Code
def read_file_safely(filename):
"""Read a file safely, returning None if it fails."""
try:
with open(filename, 'r') as f:
return f.read()
except FileNotFoundError:
print(f"❌ Error: '{filename}' does not exist.")
return None
except PermissionError:
print(f"❌ Error: No permission to read '{filename}'.")
return None
except Exception as e:
print(f"❌ Unexpected error: {e}")
return None
content = read_file_safely("example.txt")
if content:
print(f"File loaded ({len(content)} chars)")
missing = read_file_safely("nonexistent.txt")
print(f"Result: {missing}") # None
8 Coding Challenge
Build a simple student grade tracker that:
- Writes 5 students with name, score to a CSV file
- Reads the CSV back and calculates the class average
- Writes a summary JSON file with: total students, average, highest score, lowest score
- Appends a log entry to "log.txt" with the current date and summary info
- Handles FileNotFoundError if any file is missing