with open("hello.txt", "w", encoding="utf-8") as f: f.write("Hello\n") f.write("Python file I/O\n")
Reading a File
# Read entire filewith open("hello.txt", "r", encoding="utf-8") as f: content = f.read() print(content)# Read line by linewith open("hello.txt", "r", encoding="utf-8") as f: for line in f: print(line.strip())
File Modes
Mode
Description
r
Read (default)
w
Write (overwrite)
a
Append
x
Create new file (error if already exists)
rb / wb
Binary read/write
CSV File Processing
import csv# Write CSVdata = [["Name", "Age", "City"], ["Alice", 25, "Seoul"], ["Bob", 30, "Busan"]]with open("data.csv", "w", newline="", encoding="utf-8") as f: writer = csv.writer(f) writer.writerows(data)# Read CSVwith open("data.csv", "r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: print(f"{row['Name']} - age {row['Age']}")
Checking File Existence
from pathlib import Pathfile_path = Path("hello.txt")if file_path.exists(): print(f"File size: {file_path.stat().st_size} bytes")else: print("File does not exist")
Today’s Exercises
Create a notepad that takes user input and appends each line to a text file.
Write a program that calculates the average of a specific column from a CSV file.
Write a program that counts the words, lines, and characters in a text file.