Chapter 8: File I/O
Learn to read and write text, CSV, and binary files from the console using Python.
Downloadchapter8.py
Objectives
- Open files in text and binary modes for reading and writing.
- Read entire file, line by line, or in chunks.
- Write text and binary data, use
writelines()
. - Use the
csv
module to parse and generate CSV files. - Manage files safely with context managers (
with
statement).
1. Reading Text Files
Open in read mode ('r'
), then:
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read() # entire file as one string
lines = f.readlines() # list of lines
f.seek(0) # go back to start
for line in f: # iterate line by line
print(line.strip())
2. Writing Text Files
Open in write ('w'
) or append ('a'
) mode:
lines = ["First line\n", "Second line\n"]
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Header\n")
f.writelines(lines) # write multiple lines at once
Modes:
Mode | Meaning |
---|---|
'r' | Read (default), file must exist |
'w' | Write, truncate or create |
'a' | Append, create if not exists |
'r+' | Read/write |
'b' suffix | Binary mode |
3. CSV File Handling
Use the built-in csv
module:
a) Reading CSV
import csv
with open("records.csv", newline="", encoding="utf-8") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row) # each row is a list of strings
b) Writing CSV
import csv
rows = [["Name","Age"], ["Alice","30"], ["Bob","25"]]
with open("out.csv", "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
writer.writerows(rows)
4. Binary File I/O
Open in binary mode ('rb'
, 'wb'
):
# Read image bytes
with open("image.png", "rb") as fin:
data = fin.read()
# Write bytes to new file
with open("copy.png", "wb") as fout:
fout.write(data)
Exercises
- Create a text file with ten lines, then write a script to count and print the number of lines.
- Build a CSV file of products (name, price), then read it and calculate the total cost.
- Write a function to append a log entry with timestamp to a log file.
- Copy a binary file (e.g., an image) from source to destination using chunks.