Modules, Files, and JSON

CS 108

Modules

Exercise 12.a

Activities for CS1 in Python, Modules POGIL:

Exercise 12.b.1

What does each import statement make available?

import math
from math import sqrt
from math import sqrt, pi
import math as m

Which of the following would work after from math import sqrt?

  • sqrt(16)
  • math.sqrt(16)
  • math.pi

Exercise 12.b.2

Consider this file greet.py:

def hello(name):
    return f"Hello, {name}!"

if __name__ == "__main__":
    print(hello("World"))
  1. What happens when you run greet.py in Thonny directly?
  2. What happens when another file does import greet?
  3. Why is the if __name__ == "__main__": guard useful?

Exercise 12.b.3

Write a module stats.py that:

  1. Defines a function average(numbers) that returns the mean of a list.
  2. Defines a function maximum(numbers) that returns the largest value.
  3. Includes a __main__ block that tests both functions on a sample list.

Then, in a separate file, import and use both functions.

Files

Files

  • full path (/Users/me/Documents/Research/experiment1.csv). includes:
    • name (make it meaningful, not untitled5023.py)
    • extension: indicates its type (e.g., .csv, .py, .docx)
    • path: where to find it
  • contents: sequence of bytes (basically a string)

Aside: organize your files!

  • Meaningful folders (by project, by class)
  • Backed up! (easiest: use OneDrive or similar)

Reading Files: all at once

filename = "haiku.txt"
text = open(filename).read()
type(text)
str
text[:25]
'An old silent pond\nA frog'

File not found?

  • URL: world-wide unambiguous name for a file (but on a website, often needs to be downloaded)
  • Full path: unambiguous name for a file — on a specific computer!
  • Relative path: depends on working folder (aka current directory)
    • "data.csv" actually means os.getcwd() + "/" + "data.csv"
    • Thonny sets working folder to the folder containing the .py file
  • So either:
    • Use a full path to the file
    • or (preferred): put the file you need right next to your script
    • … or in a data folder and use data/data.csv

What results?

filename = "haiku.txt"
text = open(filename).read()
type(text)

Reading Files

The content of a file is just a string. (maybe really long)

text = open("haiku.txt").read()
print(repr(text[:50])) # <- show just the first 50 characters
'An old silent pond\nA frog jumps into the pond\nSpla'

We can split it into lines:

lines = text.splitlines() # <- almost the same as text.split('\n')
for line in lines:
  print(line)
An old silent pond
A frog jumps into the pond
Splash! Silence again

Reading Files: line by line

lines = open("haiku.txt").read().splitlines()
for line in lines:
  print(line)
An old silent pond
A frog jumps into the pond
Splash! Silence again

Exercise 12.c.1

A file haiku.txt contains:

An old silent pond
A frog jumps into the pond
Splash! Silence again

Write code using open to:

  1. Read and print every line.
  2. Count and print the total number of lines.

Exercise 12.c.2

Write a function save_list(filename, items) that writes each item in items to its own line in a file.

Then write load_list(filename) that reads the file back and returns a list of strings (with whitespace stripped).

Test both functions with a short list of words.

Exercise 12.c.3

The following JSON file player.json holds game data:

{
  "name": "Alex",
  "score": 4200,
  "level": 7,
  "achievements": ["first_win", "speed_run"]
}

Write code to:

  1. Load the file with json.load.
  2. Print the player’s name and score.
  3. Add a new achievement "collector" to the list.
  4. Save the updated data back to the file with json.dump.

Exercise 12.d

A scores.json file stores a list of player records, each with "name" and "score" keys.

  1. Load the file.
  2. Find and print the name of the player with the highest score. Use max(..., key=...).
  3. Add a new player record and save the updated list back to the file.

Exercise 12.e

Consider: your phone stores your photos locally and backs them up to the cloud. Your messages are synced across devices. Your game saves to a local file.

  • What are the tradeoffs between storing data locally (files) vs. on a server?
  • Who owns the data in each case?
  • What happens if the company shuts down?

How should software designers think about these tradeoffs?