π Exercise Twelve: File Input and Output
Up until now, all the data in your programs has been either hard-coded or entered by the user at runtime. But what happens when you have thousands or millions of data points? You certainly can't type them all in every time you run your program! This is where file input and output (I/O) becomes essential. Files allow your programs to read data from external sources and save results for later use.
- How to open, read, and close files
- Different file modes (read, write, append)
- How to read files line by line
- How to write data to files
- Working with structured data (CSV files)
- Processing large data files efficiently
Think of file I/O like working with a physical filing cabinet:
- Opening a file = Taking a folder out of the cabinet
- Reading a file = Looking at the contents of the folder
- Writing to a file = Adding or changing documents in the folder
- Closing a file = Putting the folder back in the cabinet
Just like you wouldn't leave a filing cabinet drawer open all day, you should always close files when you're done with them!
β 1. Why Use Files?
Files are essential for many real-world programming tasks:
- Data Analysis: Read thousands of measurements from a data file
- Configuration: Store program settings that persist between runs
- Logging: Keep a record of what your program did
- Data Exchange: Share data between different programs
- Reports: Generate output files with results
- Persistence: Save user data so it's not lost when the program ends
π 2. Opening and Closing Files
Before you can read from or write to a file, you must open it. When you're done, you should close it.
Basic File Opening
# Open a file for reading
file = open("myfile.txt", "r")
# Do something with the file...
# Close the file when done
file.close()File Modes
The second argument to open() specifies the modeβwhat you want to do with the file:
| Mode | Name | Description | If File Doesn't Exist |
|---|---|---|---|
"r" |
Read | Read only (default) | Error |
"w" |
Write | Write only (overwrites existing content!) | Creates new file |
"a" |
Append | Add to end of file | Creates new file |
"r+" |
Read/Write | Both read and write | Error |
"w" mode on an existing file will erase all its contents! Be very careful when writing to files. If you want to add to an existing file, use "a" (append) mode instead.
The Better Way: Using with Statement
Python provides a safer and cleaner way to work with files using the with statement. This automatically closes the file when you're done, even if an error occurs:
# The recommended way to open files
with open("myfile.txt", "r") as file:
# Do something with the file
content = file.read()
print(content)
# File is automatically closed here!with?
- Automatically closes the file when the block ends
- Closes the file even if an error occurs inside the block
- Cleaner, more readable code
- Prevents resource leaks (forgetting to close files)
π 3. Reading from Files
Let's create a sample text file and learn different ways to read it. First, imagine we have a file called sample.txt:
This is line 2.
Python is fun!
This is the last line.
Method 1: Read Entire File at Once
The read() method reads the entire file into a single string:
with open("sample.txt", "r") as file:
content = file.read()
print(content)
print("---")
print("Type:", type(content))
print("Length:", len(content), "characters")This is line 2.
Python is fun!
This is the last line.
---
Type: <class 'str'>
Length: 64 characters
Method 2: Read All Lines into a List
The readlines() method reads all lines into a list, where each line is a separate string:
with open("sample.txt", "r") as file:
lines = file.readlines()
print("Number of lines:", len(lines))
print("Lines:", lines)Lines: ['Hello, World!\n', 'This is line 2.\n', 'Python is fun!\n', 'This is the last line.']
\n?
Each line includes the newline character (\n) at the end. You can remove it using strip():
line = "Hello, World!\n"
clean_line = line.strip() # Removes leading/trailing whitespace
print(clean_line) # "Hello, World!"Method 3: Read Line by Line (Best for Large Files)
For large files, reading line by line is memory-efficient because you only load one line at a time:
with open("sample.txt", "r") as file:
line_number = 1
for line in file:
clean_line = line.strip() # Remove newline character
print("Line " + str(line_number) + ": " + clean_line)
line_number += 1Line 2: This is line 2.
Line 3: Python is fun!
Line 4: This is the last line.
Method 4: Read One Line at a Time with readline()
with open("sample.txt", "r") as file:
first_line = file.readline()
second_line = file.readline()
print("First:", first_line.strip())
print("Second:", second_line.strip())Second: This is line 2.
Comparison: Which Method to Use?
| Method | Returns | Best For |
|---|---|---|
read() |
Entire file as one string | Small files you need as a whole |
readlines() |
List of all lines | When you need random access to lines |
for line in file: |
One line at a time | Large files (memory efficient!) |
readline() |
Single line | When you only need specific lines |
βοΈ 4. Writing to Files
Writing with "w" Mode (Overwrite)
This creates a new file or replaces an existing file's contents:
# Write to a file (creates new or overwrites existing)
with open("output.txt", "w") as file:
file.write("This is line 1\n")
file.write("This is line 2\n")
file.write("This is line 3\n")
print("File written successfully!")
# Verify by reading it back
with open("output.txt", "r") as file:
print(file.read())This is line 1
This is line 2
This is line 3
write() method does NOT automatically add newlines. You must include \n yourself if you want lines to be separated.
Writing Multiple Lines with writelines()
lines = [
"First line\n",
"Second line\n",
"Third line\n"
]
with open("output.txt", "w") as file:
file.writelines(lines)
print("Lines written!")Appending with "a" Mode
Append mode adds to the end of an existing file without erasing its contents:
# First, create a file with some content
with open("log.txt", "w") as file:
file.write("Program started\n")
# Later, append more content
with open("log.txt", "a") as file:
file.write("Processing data...\n")
# Append even more
with open("log.txt", "a") as file:
file.write("Program finished\n")
# Read the complete file
with open("log.txt", "r") as file:
print(file.read())Processing data...
Program finished
Writing Data from Variables
# Calculate some results and save them
numbers = [10, 20, 30, 40, 50]
total = sum(numbers)
average = total / len(numbers)
with open("results.txt", "w") as file:
file.write("=== Data Analysis Results ===\n")
file.write("\n")
file.write("Numbers: " + str(numbers) + "\n")
file.write("Count: " + str(len(numbers)) + "\n")
file.write("Sum: " + str(total) + "\n")
file.write("Average: " + str(average) + "\n")
print("Results saved to results.txt")Numbers: [10, 20, 30, 40, 50]
Count: 5
Sum: 150
Average: 30.0
π 5. Working with CSV Files
CSV (Comma-Separated Values) is one of the most common formats for storing structured data. Each line represents a record, and values within a record are separated by commas.
Alice,20,Junior,3.8
Bob,19,Sophomore,3.2
Charlie,21,Senior,3.9
Diana,20,Junior,3.5
Eve,22,Senior,3.7
Visual Representation:
| name | age | grade | gpa |
|---|---|---|---|
| Alice | 20 | Junior | 3.8 |
| Bob | 19 | Sophomore | 3.2 |
| Charlie | 21 | Senior | 3.9 |
| Diana | 20 | Junior | 3.5 |
| Eve | 22 | Senior | 3.7 |
Reading CSV Files Manually (Using split())
You can parse CSV files by splitting each line on the comma:
# Read and parse a CSV file manually
with open("students.csv", "r") as file:
# Read the header line
header = file.readline().strip()
columns = header.split(",")
print("Columns:", columns)
print()
# Read each data line
for line in file:
values = line.strip().split(",")
name = values[0]
age = int(values[1])
grade = values[2]
gpa = float(values[3])
print(name + " is " + str(age) + " years old, a " + grade + " with GPA " + str(gpa))Alice is 20 years old, a Junior with GPA 3.8
Bob is 19 years old, a Sophomore with GPA 3.2
Charlie is 21 years old, a Senior with GPA 3.9
Diana is 20 years old, a Junior with GPA 3.5
Eve is 22 years old, a Senior with GPA 3.7
Storing CSV Data in a List of Lists
# Read CSV into a 2D list
data = []
with open("students.csv", "r") as file:
# Skip header
header = file.readline().strip().split(",")
# Read all data rows
for line in file:
values = line.strip().split(",")
data.append(values)
print("Header:", header)
print("Number of records:", len(data))
print()
print("All data:")
for row in data:
print(row)Number of records: 5
All data:
['Alice', '20', 'Junior', '3.8']
['Bob', '19', 'Sophomore', '3.2']
['Charlie', '21', 'Senior', '3.9']
['Diana', '20', 'Junior', '3.5']
['Eve', '22', 'Senior', '3.7']
Writing CSV Files
# Data to write
students = [
["Alice", 20, "Junior", 3.8],
["Bob", 19, "Sophomore", 3.2],
["Charlie", 21, "Senior", 3.9]
]
with open("new_students.csv", "w") as file:
# Write header
file.write("name,age,grade,gpa\n")
# Write each student
for student in students:
# Convert all values to strings and join with commas
line = ",".join([str(value) for value in student])
file.write(line + "\n")
print("CSV file created!")join() Method:
",".join(list) combines all elements of a list into a single string, with commas between them. For example, ",".join(["a", "b", "c"]) produces "a,b,c".
π 6. Processing Large Data Files
Now let's put it all together! Here's how to read a large data file, extract information, and perform analysis.
Example: Weather Data Analysis
Imagine we have a file with thousands of temperature readings:
2024-01-01,New York,32,65
2024-01-01,Los Angeles,68,45
2024-01-01,Chicago,28,70
2024-01-02,New York,35,60
2024-01-02,Los Angeles,72,42
2024-01-02,Chicago,25,75
... (thousands more rows)
# Process a large weather data file
def analyze_weather_data(filename):
"""Read weather data and calculate statistics by city"""
# Dictionary to store temperatures for each city
city_temps = {}
total_records = 0
with open(filename, "r") as file:
# Skip header
header = file.readline()
# Process each line
for line in file:
values = line.strip().split(",")
date = values[0]
city = values[1]
temperature = float(values[2])
humidity = int(values[3])
# Add temperature to city's list
if city not in city_temps:
city_temps[city] = []
city_temps[city].append(temperature)
total_records += 1
# Calculate statistics for each city
print("=== Weather Data Analysis ===")
print("Total records processed:", total_records)
print()
for city in city_temps:
temps = city_temps[city]
avg_temp = sum(temps) / len(temps)
min_temp = min(temps)
max_temp = max(temps)
print(city + ":")
print(" Records:", len(temps))
print(" Average temp:", round(avg_temp, 1))
print(" Min temp:", min_temp)
print(" Max temp:", max_temp)
print()
# Run the analysis
analyze_weather_data("weather_data.csv")Total records processed: 6
New York:
Records: 2
Average temp: 33.5
Min temp: 32
Max temp: 35
Los Angeles:
Records: 2
Average temp: 70.0
Min temp: 68
Max temp: 72
Chicago:
Records: 2
Average temp: 26.5
Min temp: 25
Max temp: 28
Example: Finding Specific Records
def find_hot_days(filename, threshold):
"""Find all days where temperature exceeded threshold"""
hot_days = []
with open(filename, "r") as file:
header = file.readline() # Skip header
for line in file:
values = line.strip().split(",")
date = values[0]
city = values[1]
temperature = float(values[2])
if temperature > threshold:
hot_days.append((date, city, temperature))
return hot_days
# Find days over 70 degrees
results = find_hot_days("weather_data.csv", 70)
print("Days with temperature above 70Β°F:")
for date, city, temp in results:
print(" " + date + " - " + city + ": " + str(temp) + "Β°F")2024-01-02 - Los Angeles: 72.0Β°F
Example: Filtering and Saving Results
def extract_city_data(input_file, output_file, target_city):
"""Extract data for a specific city and save to new file"""
records_found = 0
with open(input_file, "r") as infile:
with open(output_file, "w") as outfile:
# Copy header
header = infile.readline()
outfile.write(header)
# Process each line
for line in infile:
values = line.strip().split(",")
city = values[1]
if city == target_city:
outfile.write(line)
records_found += 1
print("Extracted " + str(records_found) + " records for " + target_city)
print("Saved to " + output_file)
# Extract New York data to a separate file
extract_city_data("weather_data.csv", "new_york_weather.csv", "New York")Saved to new_york_weather.csv
π― 7. Complete Examples
Example 1: Student Grade Report Generator
# Create sample grade data file first
sample_data = """student_id,name,quiz1,quiz2,quiz3,midterm,final
101,Alice,85,90,88,92,95
102,Bob,78,82,75,80,85
103,Charlie,92,95,98,94,96
104,Diana,70,65,72,68,75
105,Eve,88,90,85,89,92"""
with open("grades.csv", "w") as file:
file.write(sample_data)
# Now process the grade file
def generate_grade_report(input_file, output_file):
"""Read grades and generate a report with averages"""
with open(input_file, "r") as infile:
with open(output_file, "w") as outfile:
# Write report header
outfile.write("=" * 50 + "\n")
outfile.write("STUDENT GRADE REPORT\n")
outfile.write("=" * 50 + "\n\n")
# Skip header in input
header = infile.readline()
all_averages = []
for line in infile:
values = line.strip().split(",")
student_id = values[0]
name = values[1]
# Get all numeric grades
grades = []
for i in range(2, len(values)):
grades.append(float(values[i]))
average = sum(grades) / len(grades)
all_averages.append(average)
# Determine letter grade
if average >= 90:
letter = "A"
elif average >= 80:
letter = "B"
elif average >= 70:
letter = "C"
elif average >= 60:
letter = "D"
else:
letter = "F"
# Write student report
outfile.write("Student: " + name + " (ID: " + student_id + ")\n")
outfile.write("Average: " + str(round(average, 1)) + "\n")
outfile.write("Grade: " + letter + "\n")
outfile.write("-" * 30 + "\n")
# Write class summary
class_avg = sum(all_averages) / len(all_averages)
outfile.write("\n" + "=" * 50 + "\n")
outfile.write("CLASS SUMMARY\n")
outfile.write("Total Students: " + str(len(all_averages)) + "\n")
outfile.write("Class Average: " + str(round(class_avg, 1)) + "\n")
outfile.write("=" * 50 + "\n")
print("Report generated: " + output_file)
# Generate the report
generate_grade_report("grades.csv", "grade_report.txt")
# Display the report
with open("grade_report.txt", "r") as file:
print(file.read())==================================================
STUDENT GRADE REPORT
==================================================
Student: Alice (ID: 101)
Average: 90.0
Grade: A
------------------------------
Student: Bob (ID: 102)
Average: 80.0
Grade: B
------------------------------
Student: Charlie (ID: 103)
Average: 95.0
Grade: A
------------------------------
Student: Diana (ID: 104)
Average: 70.0
Grade: C
------------------------------
Student: Eve (ID: 105)
Average: 88.8
Grade: B
------------------------------
==================================================
CLASS SUMMARY
Total Students: 5
Class Average: 84.8
==================================================
Example 2: Log File Analyzer
# Create sample log file
log_data = """2024-01-15 08:30:22 INFO User login: alice
2024-01-15 08:31:45 INFO User login: bob
2024-01-15 08:35:10 ERROR Database connection failed
2024-01-15 08:35:15 INFO Database reconnected
2024-01-15 09:00:00 WARNING Low memory: 85% used
2024-01-15 09:15:30 INFO User logout: alice
2024-01-15 09:30:00 ERROR File not found: config.txt
2024-01-15 10:00:00 INFO System backup started
2024-01-15 10:30:00 INFO System backup completed
2024-01-15 11:00:00 WARNING High CPU usage: 90%"""
with open("system.log", "w") as file:
file.write(log_data)
# Analyze the log file
def analyze_log(filename):
"""Analyze log file and count message types"""
info_count = 0
warning_count = 0
error_count = 0
errors = []
with open(filename, "r") as file:
for line in file:
if "INFO" in line:
info_count += 1
elif "WARNING" in line:
warning_count += 1
elif "ERROR" in line:
error_count += 1
errors.append(line.strip())
print("=== Log Analysis ===")
print("INFO messages:", info_count)
print("WARNING messages:", warning_count)
print("ERROR messages:", error_count)
print()
print("Errors found:")
for error in errors:
print(" - " + error)
analyze_log("system.log")INFO messages: 6
WARNING messages: 2
ERROR messages: 2
Errors found:
- 2024-01-15 08:35:10 ERROR Database connection failed
- 2024-01-15 09:30:00 ERROR File not found: config.txt
Example 3: Data Transformation Pipeline
# Create sample sales data
sales_data = """date,product,quantity,price
2024-01-01,Widget,10,29.99
2024-01-01,Gadget,5,49.99
2024-01-02,Widget,8,29.99
2024-01-02,Gizmo,12,19.99
2024-01-03,Gadget,3,49.99
2024-01-03,Widget,15,29.99
2024-01-03,Gizmo,7,19.99"""
with open("sales.csv", "w") as file:
file.write(sales_data)
def create_sales_summary(input_file, output_file):
"""Read sales data and create summary by product"""
# Dictionary to accumulate sales by product
product_sales = {}
with open(input_file, "r") as file:
header = file.readline() # Skip header
for line in file:
values = line.strip().split(",")
product = values[1]
quantity = int(values[2])
price = float(values[3])
revenue = quantity * price
if product not in product_sales:
product_sales[product] = {"quantity": 0, "revenue": 0}
product_sales[product]["quantity"] += quantity
product_sales[product]["revenue"] += revenue
# Write summary to output file
with open(output_file, "w") as file:
file.write("product,total_quantity,total_revenue\n")
grand_total = 0
for product in product_sales:
qty = product_sales[product]["quantity"]
rev = product_sales[product]["revenue"]
grand_total += rev
file.write(product + "," + str(qty) + "," + str(round(rev, 2)) + "\n")
print("Sales Summary:")
print("-" * 40)
for product in product_sales:
qty = product_sales[product]["quantity"]
rev = product_sales[product]["revenue"]
print(product + ": " + str(qty) + " units, $" + str(round(rev, 2)))
print("-" * 40)
print("Grand Total: $" + str(round(grand_total, 2)))
print()
print("Summary saved to " + output_file)
create_sales_summary("sales.csv", "sales_summary.csv")----------------------------------------
Widget: 33 units, $989.67
Gadget: 8 units, $399.92
Gizmo: 19 units, $379.81
----------------------------------------
Grand Total: $1769.4
Summary saved to sales_summary.csv
π‘οΈ 8. Handling File Errors
When working with files, many things can go wrong: the file might not exist, you might not have permission to read it, or the disk might be full. It's important to handle these errors gracefully.
Using Try-Except for File Operations
def safe_read_file(filename):
"""Safely read a file with error handling"""
try:
with open(filename, "r") as file:
content = file.read()
return content
except FileNotFoundError:
print("Error: File '" + filename + "' not found.")
return None
except PermissionError:
print("Error: Permission denied to read '" + filename + "'")
return None
except Exception as e:
print("Error reading file: " + str(e))
return None
# Test with existing file
content = safe_read_file("sample.txt")
if content:
print("File read successfully!")
# Test with non-existing file
content = safe_read_file("does_not_exist.txt")Error: File 'does_not_exist.txt' not found.
Checking if a File Exists
import os
filename = "sample.txt"
if os.path.exists(filename):
print("File exists!")
with open(filename, "r") as file:
print(file.read())
else:
print("File does not exist.")β οΈ Common Mistakes (And How to Fix Them)
Mistake 1: Forgetting to Close the File
file = open("data.txt", "r")
content = file.read()
# Forgot to close! File stays open, wasting resourceswith statement):
with open("data.txt", "r") as file:
content = file.read()
# File automatically closedMistake 2: Using Wrong Mode
with open("data.txt", "w") as file:
content = file.read() # ERROR! Can't read in write modewith open("data.txt", "r") as file: # Use "r" for reading
content = file.read()Mistake 3: Forgetting Newlines When Writing
with open("output.txt", "w") as file:
file.write("Line 1")
file.write("Line 2")
file.write("Line 3")
# Result: "Line 1Line 2Line 3" (all on one line!)with open("output.txt", "w") as file:
file.write("Line 1\n")
file.write("Line 2\n")
file.write("Line 3\n")Mistake 4: Not Stripping Whitespace
with open("data.txt", "r") as file:
for line in file:
if line == "hello":
print("Found it!") # Never matches! line is "hello\n"with open("data.txt", "r") as file:
for line in file:
if line.strip() == "hello":
print("Found it!")Mistake 5: Accidentally Overwriting Data
# Trying to add to a log file
with open("log.txt", "w") as file: # OOPS! "w" erases everything!
file.write("New entry\n")# Use "a" to append to existing content
with open("log.txt", "a") as file:
file.write("New entry\n")βοΈ Practice Exercises
Try writing these programs on your own!
Exercise 1: Line Counter
Write a program that:
- Asks the user for a filename
- Opens the file and counts the number of lines
- Counts the number of words (hint: use
split()) - Counts the number of characters
- Displays all three counts
Exercise 2: Number File Processor
Create a file with one number per line. Write a program that:
- Reads all the numbers from the file
- Calculates the sum, average, minimum, and maximum
- Writes the results to a new file called "statistics.txt"
Exercise 3: CSV Filter
Given a CSV file with student data (name, age, major, gpa):
- Read the file
- Filter for students with GPA above 3.5
- Write the filtered records to a new file called "honor_roll.csv"
- Display how many students made the honor roll
Exercise 4: Search and Replace
Write a program that:
- Reads a text file
- Asks the user for a word to find and a replacement word
- Replaces all occurrences of the word
- Writes the result to a new file
- Reports how many replacements were made
Exercise 5: Merge Files
Write a program that:
- Takes a list of input filenames
- Reads all files
- Combines their contents into a single output file
- Adds a separator line between each file's content
Exercise 6: Data Analysis Challenge
Create a CSV file with at least 20 rows of product sales data (date, product, quantity, price). Write a program that:
- Calculates total revenue per product
- Finds the best-selling product (by quantity)
- Finds the highest revenue product
- Calculates average sale amount
- Generates a formatted report file
π Quick Reference
Opening Files
with open("file.txt", "r") as f:
content = f.read()with open("file.txt", "w") as f:
f.write("text")with open("file.txt", "a") as f:
f.write("more text")Reading Methods
content = file.read()lines = file.readlines()line = file.readline()for line in file:
print(line.strip())Writing Methods
file.write("text\n")file.writelines(list_of_strings)β Key Takeaways
- β Use
open(filename, mode)to open files; mode can be"r","w", or"a" - β Always use the
withstatementβit automatically closes files - β
"w"mode overwrites existing files; use"a"to append - β
read()gets entire file; iterate withfor line in file:for large files - β Use
strip()to remove newline characters from lines - β Use
split(",")to parse CSV data - β Don't forget
\nwhen writing lines - β Handle errors with try-except for robust programs
- β Process large files line by line to save memory
- β Close files properly to avoid resource leaks
β Need Help?
If your program doesn't work, check these common issues:
- FileNotFoundErrorβIs the file in the same directory as your Python script? Check the path!
- Lines appear on one lineβDid you include
\nwhen writing? - Comparisons not workingβDid you
strip()the newlines? - File is empty after writingβDid you close the file (or use
with)? - Data lostβDid you accidentally use
"w"instead of"a"?
with open("data.txt", "r") as file:
for line in file:
print("Raw line:", repr(line)) # Shows \n and spaces
print("Stripped:", line.strip())with statement, handle errors gracefully, and process large files line by line to keep memory usage low. With these skills, you're ready to tackle serious data processing tasks!