# Modes:
# 'r' - Read (default, error if doesn't exist)
# 'w' - Write (creates new or TRUNCATES existing)
# 'a' - Append (creates new or adds to end)
# 'r+' - Read and write (doesn't truncate)
# 'x' - Exclusive creation (error if file exists)
# ALWAYS use 'with' statement!
with open('data.txt', 'r') as f:
content = f.read()
# File is automatically closed here, even if error occurs
# ❌ BAD (manual close, risky)
f = open('data.txt')
content = f.read()
f.close() # What if read() crashes? File stays open!with open('data.txt', 'r') as f:
# Read entire file as string
content = f.read()
# Read N characters
# first_10 = f.read(10)
with open('data.txt', 'r') as f:
# Read line by line (memory efficient for large files)
for line in f:
print(line.strip()) # .strip() removes \n
with open('data.txt', 'r') as f:
# Read all lines into list (includes \n at end of each!)
lines = f.readlines()
# ['line1\n', 'line2\n']
with open('data.txt', 'r') as f:
# Read single line
first_line = f.readline()# Write (OVERWRITES existing content!)
with open('output.txt', 'w') as f:
f.write('Hello\n')
f.write('World\n')
# Write multiple lines (adds \n automatically)
f.writelines(['Line 1\n', 'Line 2\n', 'Line 3\n'])
# Append (adds to end, keeps existing content)
with open('output.txt', 'a') as f:
f.write('Appended line\n')with open('data.txt', 'r') as f:
print(f.tell()) # 0 (current position)
first_5 = f.read(5)
print(f.tell()) # 5
f.seek(0) # Go back to start
content = f.read() # Reads from start again# Read file into list of clean lines
def read_lines(filepath):
with open(filepath, 'r') as f:
return [line.strip() for line in f]
# Safe write with error handling
import os
def safe_write(filepath, content):
try:
with open(filepath, 'w') as f:
f.write(content)
return True
except IOError as e:
print(f'Error: {e}')
return False
# Check if file exists before reading
if os.path.exists('data.txt'):
with open('data.txt') as f:
data = f.read()Create a function `word_count(filepath)` that reads a text file and returns a dictionary of word frequencies (case-insensitive, ignore punctuation). Create a function `write_report(filepath, data_dict)` that writes a formatted report to a file where each line is `"Key: Value"` sorted by key name. Use `with` statements for all file operations.