File I/O Exercises
Objectives
This chapter introduces no new concepts: it’s a chance to put text file, CSV, and JSON I/O into practice.
Part I: Text Files
Assume you have a file called students.txt containing a bunch of student names, one per line. Write two functions:
add_student(first_name): appends a new name tostudents.txt.find_student(first_name): returns the first matching student found in the file.
Bonuses
- Add these two functions as well:
update_student(first_name, new_name): finds the first matching student and updates their name.remove_student(first_name): finds and removes a student from the file.
- Give each student a unique id, so you can look one up by id instead of by first name (first names alone break down once two students share one).
Part II: CSV
Create a file called users.csv, then write:
- A function that prints out every first and last name in
users.csv. - A function that prompts the user to enter a first and last name, then appends it to
users.csv.
Part III: JSON
Write two functions that work against a file called settings.json:
save_settings(settings): accepts a dictionary and writes it tosettings.json, formatted withindent=2so it’s readable.load_settings(): readssettings.jsonand returns it as a Python dictionary. If the file doesn’t exist yet, return an empty dictionary instead of raising an error.
Bonus: write an update_setting(key, value) function that loads the existing settings, updates a single key, and saves the whole thing back, without disturbing any of the other keys already in the file.
Try It
- Implement
add_studentandfind_studentagainst a realstudents.txtfile, and test both. - Attempt the bonus
update_student/remove_studentfunctions, or the unique-id extension. - Build the two CSV functions from Part II and test them against a
users.csvyou create yourself. - Build
save_settingsandload_settingsfrom Part III, and confirm the round trip preserves your data exactly.
Recap
You can now read from and write to plain text files using the with statement and the right file mode, read and write CSV files using csv.reader, csv.DictReader, csv.writer, and csv.DictWriter, and read and write JSON files with json.load and json.dump. That’s the full toolkit this module set out to build.
Next lesson: a mini project. Build a file-backed expense tracker using everything from this module.