Files: Text, CSV and JSON

Make your programs remember. You'll read and write text files with open and with, read a spreadsheet's rows from a CSV file and write a new one, and save your program's data as JSON so it's there next time. Then you'll keep a running club's log: who ran how far, and the goals each member set.

Updated

Text Files

  1. Reading and Writing Text Files (Apprentice): open() in a with block writes text to a file and reads it back, the mode says whether to write ("w"), add to the end ("a") or read ("r"), encoding="utf-8" keeps every letter intact, and a FileNotFoundError means the name or the folder is wrong.

CSV and JSON

  1. CSV Files: Tables in Plain Text (Apprentice): A CSV file is a table in plain text that every spreadsheet can open and save, and Python's csv module writes it with DictWriter and reads it with reader or DictReader, giving back every value as text that you convert to numbers with int() and float().
  2. JSON Files: Saving Your Data (Apprentice): JSON is a text format for data that json.dump and json.load turn Python's dictionaries and lists into and back from, through a file, while json.dumps and json.loads do the same with a string, which is how web APIs send their answers.

Exercise: Running Club Log

  1. Exercise: Running Club Log (Journeyman): Write the five functions behind a running club's weekly log, reading its runs from a CSV file, totaling each runner's miles, writing a summary CSV and saving and loading goals as JSON, and let pytest's tests check each one in folders of their own.