Module 11: Practice Problems
15 problems to practice file handling in Python
Problem 1 Easy
Write code that creates a file called hello.txt and writes "Hello, World!" to it using the with statement.
Use with open("hello.txt", "w") as file: and then file.write().
with open("hello.txt", "w") as file: file.write("Hello, World!")
Problem 2 Easy
Read the entire contents of a file called hello.txt and print it.
Use with open("hello.txt", "r") as file: and file.read().
with open("hello.txt", "r") as file: content = file.read() print(content)
Problem 3 Easy
Write a list of three favorite foods to a file called foods.txt, one per line.
Remember to add \n after each food name.
foods = ["Pizza", "Sushi", "Tacos"] with open("foods.txt", "w") as file: for food in foods: file.write(food + "\n")
Problem 4 Easy
Read a file line by line and print each line with its line number.
Use enumerate() with a start value of 1 inside a for loop.
with open("foods.txt", "r") as file: for num, line in enumerate(file, 1): print(f"Line {num}: {line.strip()}")
Problem 5 Easy
Append the text "Added later!" to an existing file called hello.txt.
Use mode "a" for append.
with open("hello.txt", "a") as file: file.write("\nAdded later!")
Problem 6 Medium
Read a file and count how many lines it contains. Print the count.
Use readlines() and len(), or count in a loop.
with open("foods.txt", "r") as file: lines = file.readlines() print(f"File has {len(lines)} lines")
Problem 7 Medium
Write a program that reads a file and counts how many words it contains.
Read the file, use split() to break into words, then count.
with open("hello.txt", "r") as file: content = file.read() words = content.split() print(f"Word count: {len(words)}")
Problem 8 Medium
Write numbers 1 through 10 to a file called numbers.txt, one per line. Then read the file back and print the sum.
Write with a loop, then read and convert each line to int before summing.
# Write with open("numbers.txt", "w") as file: for i in range(1, 11): file.write(f"{i}\n") # Read and sum with open("numbers.txt", "r") as file: total = sum(int(line.strip()) for line in file) print(f"Sum: {total}") # 55
Problem 9 Medium
Copy the contents of one file to another using the with statement.
Nest two with statements - one for reading, one for writing.
with open("hello.txt", "r") as source: with open("hello_copy.txt", "w") as dest: for line in source: dest.write(line) print("File copied!")
Problem 10 Medium
Create a CSV file called products.csv with columns: name, price, quantity. Add at least 3 products.
Use csv.writer with writerow() for the header and writerows() for data.
import csv products = [ ["Laptop", 999.99, 5], ["Mouse", 29.99, 50], ["Keyboard", 79.99, 30] ] with open("products.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerow(["name", "price", "quantity"]) writer.writerows(products)
Problem 11 Medium
Read the products.csv file using DictReader and print each product's name and price.
Use csv.DictReader(file) and access columns with row['name'].
import csv with open("products.csv", "r") as file: reader = csv.DictReader(file) for row in reader: print(f"{row['name']}: ${row['price']}")
Problem 12 Hard
Write a program that reads a text file and creates a new file with all text converted to uppercase.
Read each line, convert with .upper(), and write to the new file.
with open("hello.txt", "r") as source: with open("hello_upper.txt", "w") as dest: for line in source: dest.write(line.upper()) print("Uppercase file created!")
Problem 13 Hard
Read a CSV file of products and calculate the total inventory value (price * quantity) for each product. Write results to a new CSV file.
Use DictReader to read, calculate price * quantity, then DictWriter to write with an added "total" column.
import csv with open("products.csv", "r") as infile: reader = csv.DictReader(infile) results = [] for row in reader: total = float(row["price"]) * int(row["quantity"]) results.append({ "name": row["name"], "price": row["price"], "quantity": row["quantity"], "total": f"{total:.2f}" }) with open("inventory_value.csv", "w", newline="") as outfile: fields = ["name", "price", "quantity", "total"] writer = csv.DictWriter(outfile, fieldnames=fields) writer.writeheader() writer.writerows(results)
Problem 14 Hard
Create a simple journal program. Ask the user for an entry, append it with a timestamp to journal.txt, then display all past entries.
Use append mode to add entries and read mode to display them. Use datetime for timestamps.
from datetime import datetime # Add new entry entry = input("Write your journal entry: ") timestamp = datetime.now().strftime("%Y-%m-%d %H:%M") with open("journal.txt", "a") as file: file.write(f"[{timestamp}] {entry}\n") # Display all entries print("\n--- All Entries ---") with open("journal.txt", "r") as file: for line in file: print(line.strip())
Problem 15 Hard
Write a program that reads a CSV file of student grades, calculates the class average, and writes a summary report to a text file including each student's name, grade, and whether they are above or below average.
First read all scores to calculate the average, then loop through again to compare each student.
import csv # Read student data students = [] with open("grades.csv", "r") as file: reader = csv.DictReader(file) for row in reader: students.append({ "name": row["Name"], "score": int(row["Score"]) }) # Calculate average avg = sum(s["score"] for s in students) / len(students) # Write report with open("report.txt", "w") as file: file.write(f"Class Average: {avg:.1f}\n") file.write("=" * 30 + "\n\n") for s in students: status = "Above" if s["score"] >= avg else "Below" file.write(f"{s['name']}: {s['score']} ({status} average)\n") print("Report saved!")