Chapter 8: File I/O

Learn to read and write text, CSV, and binary files from the console using Python.

Download chapter8.py

Objectives

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:

ModeMeaning
'r'Read (default), file must exist
'w'Write, truncate or create
'a'Append, create if not exists
'r+'Read/write
'b' suffixBinary 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

  1. Create a text file with ten lines, then write a script to count and print the number of lines.
  2. Build a CSV file of products (name, price), then read it and calculate the total cost.
  3. Write a function to append a log entry with timestamp to a log file.
  4. Copy a binary file (e.g., an image) from source to destination using chunks.