Skip to content

Nov 06: Prac5, Lists of Lists

Learning Objectives

After today's class, you should be able to:

  • Write code that reads or writes a file using a with statement.
  • Describe how any kind of data can be represented using JSON.

Announcements

File I/O Debrief

Refer to Monday's activity

  • Question 3: Write a file
    with open("lines.txt", "w") as file:
        for i in range(1, 101):
            file.write(f"Line #{i}\n")
    
  • Question 14: Read a file
    with open("names.txt") as file:
        for line in file:
            words = line.split()
            print(words[1])
    
  • See docs for split method

Practice Quiz 5

  • 1st sheet: "written potion"
  • 2nd sheet: "coding potion" (write code on paper)
  • 3rd sheet: Python Reference Sheetnew!
  • Turn off monitor during quiz

Ch11 Preview

  • CORGIS
    • Collection of Really Great, Interesting, Situated Datasets
  • Example: County Demographics
  • List comprehensions
    • Ex: [x ** 2 for x in range(10)]
    • Function from PA 1 can be rewritten as one line:
      def get_valid_items(size):
          return [chr(65 + i) for i in range(size)]
      

CSV example:

import csv
from pprint import pprint

data = []
with open("county_demographics.csv") as file:
    reader = csv.reader(file)
    data = [row for row in reader]

pprint(data[0])

JSON example:

import json
from pprint import pprint

with open("county_demographics.json") as file:
    data = json.load(file)

for item in data:
    if item["County"] == "Harrisonburg city":
        pprint(item)