Bitpath

Lesson 2 · Unit 06

Files and modules

Borrow ready-made code, and keep data after the program ends

13 exercisesabout 3 min

What you practise

  • with open, reading and writing lines, JSON in and out, import and the standard library (math, random, datetime, pathlib), if __name__ == "__main__"

Try a question from this lesson

Pick one

Python keeps extra tools in modules. import math loads one: math.sqrt is its square root, math.floor rounds down. What does this program show?

Python
import math

print(math.sqrt(49) + math.floor(2.9))
Hint

The square root comes back as a number with a point. Rounding down drops everything after the point.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Modules and import

A module is a file of ready-made code. Python ships with hundreds of them: the standard library.

import math loads the module, and you reach inside it with a dot. from random import choice takes one name out, so you can use it without the dot.

Python
import math
from random import choice

print(math.pi)   # 3.141592653589793
print(math.ceil(2.1))  # 3: rounds up

coin = choice(["heads", "tails"])
print(coin)      # one of the two

Concept

open, with and modes

open needs a file name and a mode. "w" writes, and wipes whatever was in the file. "a" adds to the end. No mode means read.

with gives the open file a name, here f, and closes the file when the indented block ends, even if an error happens inside it.

Python
with open("notes.txt", "w") as f:
    f.write("milk\n")

with open("notes.txt", "a") as f:
    f.write("eggs\n")

with open("notes.txt") as f:
    print(f.read())
# milk
# eggs

Concept

JSON

A file holds text. JSON is a way of writing lists and dictionaries as text, so they can be saved and read back.

json.dumps turns data into a JSON string, and json.loads turns it back. With an open file, use json.dump(data, f) and json.load(f).

Python
import json

stock = {"tea": 4, "milk": 0}
text = json.dumps(stock)
print(text)  # {"tea": 4, "milk": 0}

back = json.loads(text)
print(back["tea"] + 1)  # 5

9 more exercises in the app

  • 3× multiple choice
  • 3× type the answer
  • 2× fill the blanks
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy