Input & Output

Files, JSON, and the command line

Paolo Rota

October 7, 2026

Where we are

Until now every value our programs used was written inside the program. The one exception was input() in Lecture 4: the person at the keyboard typed something, and it came back as a string.

Useful programs work on data that lives outside them, and keep their results after they stop:

  1. Files — text on disk, read in and written out;
  2. JSON — files that already have a structure;
  3. The command line — values handed to a program as it starts.

Today’s notional machine gains one piece: the disk. Memory is wiped when a program ends; the disk is not. Writing to a file is how a result survives the program that made it.

Our course folder

From today our programs touch files, so every file needs a place. One folder for the course, open in VS Code, with two folders inside:

intro2python/          ← File → Open Folder on this
├── resources/         files I give you
│   └── mini_alice.txt
├── output/            files your programs make
│   └── notes.txt
└── today.py           your code
  • resources/ is read only. Programs read from it and never write to it: you can always trust what is in there.
  • output/ is disposable. Everything a program writes goes there. Delete it all whenever you like: run the programs again and it comes back.

In the code the folder is part of the name: "resources/mini_alice.txt", "output/notes.txt".

Data flows one way: in from resources/, out to output/. A program that writes into resources/ can destroy the data it reads.

Writing a file

Three steps: open, use, close

A program cannot touch the disk directly. It asks for a connection to one file, uses it, and hands it back:

f = open("output/notes.txt", "w", encoding="utf-8")  # open: a connection
f.write("first line\n")                               # use: send it text
f.write("second line\n")
f.close()                                             # close: hand it back

print("done — look in output/")
done — look in output/
  • "output/notes.txt" — the file’s name, inside the output/ folder. If the file does not exist, "w" creates it. The output/ folder must already exist.
  • "w" — the mode: write.
  • encoding="utf-8" — the agreement for turning characters into bits. More on this later today; for now, always write it.

open hands back a file object, and f is just a box holding it. write and close are its methods — the same value.method() you used with strings in Lecture 3.

write is not print

Predict what ends up in the file:

f = open("output/notes.txt", "w", encoding="utf-8")
f.write("one")
f.write("two")
f.write(str(3))
f.close()

f = open("output/notes.txt", "r", encoding="utf-8")  # "r": read it back
print(f.read())
f.close()
onetwo3

write adds nothing you did not ask for: no space, no newline. Every line break in a file is a \n that you wrote. And it takes one string — f.write(3) is a TypeError, which is why the str(...) is there.

The safer with block

Forget the close() and the text may never reach the disk. with closes the file for you, at the end of the block — even if an error stops the program half-way:

with open("output/notes.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")
    f.write("second line\n")
    f.write("third line\n")
# here the file is already closed

print("closed?", f.closed)          # an attribute: True once closed
closed? True

Read it as “with this file open, call it f, do the indented block — then close it”. The block is indentation again, as in an if or a for. From now on every file we open is opened with with.

"w" destroys, "a" adds

Opening with "w" empties the file first — whatever was there is gone. To add to the end instead, open it with "a", append:

with open("output/diary.txt", "w", encoding="utf-8") as f:
    f.write("Monday: rain\n")

with open("output/diary.txt", "a", encoding="utf-8") as f:
    f.write("Tuesday: sun\n")

with open("output/diary.txt", "w", encoding="utf-8") as f:
    f.write("Wednesday: fog\n")

with open("output/diary.txt", "r", encoding="utf-8") as f:
    print(f.read())
Wednesday: fog

There is no undo and no warning. Practise on toy files — never on the only copy of data you care about.

Reading a file

All at once: read()

read() hands back the whole file as one string, newlines included:

first line
second line
third line
with open("output/notes.txt", "r", encoding="utf-8") as f:
    text = f.read()

print(repr(text))                # repr: the string as stored, \n visible
print(len(text), "characters")
'first line\nsecond line\nthird line\n'
34 characters

From here it is an ordinary string, and Lecture 3 applies:

print(text.splitlines())        # one item per line, the \n removed
print(text.upper())
['first line', 'second line', 'third line']
FIRST LINE
SECOND LINE
THIRD LINE

One line at a time

A file is something a for can walk through, like a string or a list. Each round, the box gets the next line:

first line
second line
third line
with open("output/notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line)
first line

second line

third line
for x in ___ each round, x gets
"abc" one character
[3, 1, 4] one item
range(3) one number
f one line

Blank lines between them! Every line still ends with its \n, and then print adds a newline of its own: two line breaks each time.

Seeing the invisible \n

print obeys the \n (it jumps to a new line), so you never see it. repr (Lecture 5) shows the string the way Python stores it:

first line
second line
third line
with open("output/notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(repr(line), len(line))
'first line\n' 11
'second line\n' 12
'third line\n' 11

So print(line) sends two line breaks to the screen: the one inside the line, and the one print always adds at the end.

first line\n     ← from the file
\n               ← from print     →  an empty line

Getting rid of the \n

One of the two line breaks has to go. Which one?

first line
second line
third line

Fix the screen: drop print’s. It ends with "\n" by default; end="" (Lecture 3) makes it end with nothing.

with open("output/notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line, end="")
first line
second line
third line

Fix the value: drop the line’s. .strip() returns a new string without the \n (and without spaces at the two ends).

with open("output/notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        print(repr(line), len(line))
'first line' 10
'second line' 11
'third line' 10

end="" only fixes the screen. .strip() fixes the value — and it is the value you will compare, count and store. Strip as soon as you read.

Keeping the lines

To use the lines after the file is closed, put them in a list — the accumulator from Lecture 4:

first line
second line
third line
lines = []
with open("output/notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        lines.append(line.strip())

print(lines)
print(len(lines), "lines")
['first line', 'second line', 'third line']
3 lines

The with block is for talking to the file. Do the reading inside it, then close it and work on the list, which lives in ordinary memory.

A file is read once

first line
second line
third line
with open("output/notes.txt", "r", encoding="utf-8") as f:
    first = f.read()
    second = f.read()

print(len(first), len(second))
34 0

34 0. A file object has its own finger, like the instruction pointer of Lecture 1: it marks how far it has read. The first read() moved it to the end; there is nothing left for the second. To read again, open the file again — or keep what you read in a box, as on the last slide.

Where is the file?

The working directory

open("output/notes.txt") does not search your computer. It starts from one folder: the folder the program was started from, its working directory.

with open("mini_alice.txt", "r", encoding="utf-8") as f:   # forgot resources/
    text = f.read()
FileNotFoundError: [Errno 2] No such file or directory: 'mini_alice.txt'

FileNotFoundError often does not mean the file is missing. It means it is not where the program is looking. Ask the machine where that is:

import os
print(os.getcwd())          # "get current working directory"

C:\Users\sara\intro2python

Making it work every time

  • In VS Code, File → Open Folder on intro2python/. The working directory is then the folder that contains resources/ and output/.
  • In a notebook, the working directory is the notebook’s own folder: keep your notebooks in intro2python/ too, next to your scripts.
  • A file in a sub-folder: give the path from there, with forward slashes — they work on Windows and macOS alike:
open("resources/alice.txt", encoding="utf-8")

On Windows, beware of copying paths with backslashes into a string: "C:\new\text.txt" contains a \n and a \t — the newline and the tab of Lecture 3. Write "C:/new/text.txt" instead.

The encoding agreement

Lecture 1 comes back

On disk there are only bits. Turning characters into bits and back is an agreement — an encoding. Write with one, read with another, and the text comes back wrong:

with open("output/city.txt", "w", encoding="utf-8") as f:
    f.write("Città: Trento — perché no?\n")

with open("output/city.txt", "r", encoding="utf-8") as f:
    print(f.read(), end="")              # the same agreement: fine

with open("output/city.txt", "r", encoding="cp1252") as f:
    print(f.read(), end="")              # another agreement: garbage
Città: Trento — perché no?
Città: Trento — perché no?

Why we always write encoding="utf-8"

Leave the encoding out and Python uses your computer’s default. On macOS that is UTF-8. On many Windows machines — including, possibly, the exam computer — it is not.

with open("output/city.txt", "r", encoding="ascii") as f:
    print(f.read())
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)

UTF-8 is the agreement almost every text file uses today: it knows every alphabet, and the curly quotes and dashes of a real book. Write it on every open and the same program works on every computer.

When things go wrong

Some errors you can see coming

So far an error stops the program. Some of them you can predict: the user types ten instead of 10; the file is not there.

age = int("ten")
ValueError: invalid literal for int() with base 10: 'ten'

try / except says: try this; if this particular error happens, do that instead of stopping.

try:
    age = int("ten")
    print("converted:", age)
except ValueError:
    print("that was not a whole number")

print("the program carries on")
that was not a whole number
the program carries on

What the machine actually does

The finger runs the try block line by line. At the first error it jumps straight to the matching except, skipping the rest of try:

for raw in ["12", "dodici", "7"]:
    try:
        n = int(raw)
        print(raw, "->", n * 2)
    except ValueError:
        print(repr(raw), "skipped")
12 -> 24
'dodici' skipped
7 -> 14

No error: the except block is skipped, like an if whose condition is False. An error of that name: the rest of try is skipped and the except runs. Either way, the program then carries on below.

Asking until the answer is good

The validation loop of Lecture 4 crashed if the user typed a word. With try it keeps asking instead:

# age.py
while True:                          # only a break can end this loop
    raw = input("Your age: ")
    try:
        age = int(raw)
        break                        # reached only if int() worked
    except ValueError:
        print("Please type digits, e.g. 21.")

print("Next year you will be", age + 1)
(intro2python) $ python age.py
Your age: twenty
Please type digits, e.g. 21.
Your age: 21.5
Please type digits, e.g. 21.
Your age: 21
Next year you will be 22

A file that may not be there

The same idea with a file: the book is not downloaded yet, and the program says so instead of crashing.

try:
    with open("resources/alice.txt", "r", encoding="utf-8") as f:
        text = f.read()
    print(len(text), "characters read")
except FileNotFoundError:
    print("No resources/alice.txt: check the name and the working directory")
163950 characters read

Inside try, put only the line that can fail and the lines that make sense only if it worked. Here the print belongs in the try: without the file there is nothing to count.

Name the error you expect

An except with no name catches everything — including your own typos:

raw = "21"
try:
    age = int(rew)          # a typo: rew, not raw
except:
    print("that was not a whole number")
that was not a whole number

The real error was a NameError, and the message blames the user. A bare except turns a bug you could fix in a second into a lie. Always name the error you are prepared to handle, and let every other one stop the program.

A real text: a book

Project Gutenberg

gutenberg.org gives away tens of thousands of books as plain text. Alice’s Adventures in Wonderland is book number 11: download Plain Text UTF-8 and save it as alice.txt, in resources/.

Every Gutenberg file wraps the book in a licence, before and after, between two marker lines:

The Project Gutenberg eBook of Alice’s Adventures in Wonderland
…
*** START OF THE PROJECT GUTENBERG EBOOK ALICE’S ADVENTURES IN WONDERLAND ***
CHAPTER I.
Down the Rabbit-Hole
…
*** END OF THE PROJECT GUTENBERG EBOOK ALICE’S ADVENTURES IN WONDERLAND ***
…

The licence is not the same length in every book, so “skip the first 52 lines” works for one file and silently breaks on the next. Look for the markers instead.

Our miniature book

The slides run on a tiny Gutenberg-style file from resources/, with the same markers as the real one:

The Project Gutenberg eBook of Alice's Adventures in Wonderland
This eBook is for the use of anyone anywhere...

*** START OF THE PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND ***
CHAPTER I.
Down the Rabbit-Hole

Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into
the book her sister was reading, but it had no pictures or
conversations in it, “and what is the use of a book,” thought Alice
“without pictures or conversations?”
*** END OF THE PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND ***
Updated editions will replace the previous one...

Just the book

A function, so that we can reuse it on any Gutenberg file:

def read_book(path):
    body = []
    inside = False
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            if line.startswith("*** END OF"):
                break                      # the book is over
            if inside:
                body.append(line.strip())
            if line.startswith("*** START OF"):
                inside = True              # from the NEXT line on
    return body

book = read_book("resources/mini_alice.txt")
print(len(book), "lines")
print(book[:3])
8 lines
['CHAPTER I.', 'Down the Rabbit-Hole', '']

From lines to words

words = []
for line in book:
    words = words + line.split()         # + joins two lists

print(len(words), "words")
print(words[-8:])
62 words
['a', 'book,”', 'thought', 'Alice', '“without', 'pictures', 'or', 'conversations?”']

split() cuts at white space and nothing else, so punctuation stays glued on: book,” and “without are not words anyone would count. We take them off by hand for now; Lecture 9 does it properly with regular expressions.

Counting word lengths

How many words have 1 letter, 2 letters, 3…? Count only the letters, so that book,” has length 4:

lengths = {}
for word in words:
    n = 0
    for ch in word.lower():
        if ch in "abcdefghijklmnopqrstuvwxyz":
            n += 1
    lengths[n] = lengths.get(n, 0) + 1

print(lengths)
{7: 6, 1: 2, 4: 8, 3: 16, 10: 1, 5: 4, 9: 1, 2: 16, 6: 4, 8: 2, 13: 2}

Read in → process → write out

Save the table to a file, one length per line, shortest first:

with open("output/lengths.txt", "w", encoding="utf-8") as out:
    for n in sorted(lengths):            # the keys, in order
        out.write(f"{n}\t{lengths[n]}\n")

with open("output/lengths.txt", "r", encoding="utf-8") as f:
    print(f.read())
1   2
2   16
3   16
4   8
5   4
6   4
7   6
8   2
9   1
10  1
13  2

Read data in from resources/, process it in memory, write the result out to output/. Almost every program you will write in this course has this shape.

Structured files: JSON

A file that already has a shape

Everything we read so far was plain text: we opened it, split it, and put the structure back by hand.

JSON (JavaScript Object Notation, though no JavaScript is needed) is plain text too, but written with rules, so that a program can rebuild the structure for you: names and values, lists, lists inside names, and so on.

A Python dictionary

{
  "name": "Sara",
  "age": 21,
  "enrolled": True
}

The same thing, as JSON text

{
  "name": "Sara",
  "age": 21,
  "enrolled": true
}

Almost the same, with three rules JSON does not bend: double quotes only, true / false / null in lower case, and no trailing comma.

JSON { ... } object [ ... ] array "text" 3, 2.5 true / false null
Python dict list str int, float True / False None

Text in, values out

A dictionary is a value in memory; JSON is text. json.loads turns one into the other:

import json

# triple quotes: a string that spans many lines
text = """[
  {"name": "Sara",  "surname": "Rossi",   "age": 21, "enrolled": true},
  {"name": "Carlo", "surname": "Bianchi", "age": 32, "enrolled": false}
]"""

people = json.loads(text)
print(type(text), type(people), type(people[0]))
print(people[0]["name"], people[0]["enrolled"])
<class 'str'> <class 'list'> <class 'dict'>
Sara True

From there it is ordinary Python — a list of dictionaries, exactly as in Lecture 3:

for person in people:
    if person["enrolled"]:
        print(person["name"], "is enrolled")
Sara is enrolled

Reading and writing a JSON file

With a file, it is the with block you already know — dump to write, load to read:

people.append({"name": "Arianna", "surname": "Verdi", "age": 21, "enrolled": True})

with open("output/students.json", "w", encoding="utf-8") as f:
    json.dump(people, f, indent=2)       # indent=2: one item per line

with open("output/students.json", "r", encoding="utf-8") as f:
    again = json.load(f)                 # file -> list of dictionaries

print(len(again), "people;", again[2]["name"], again[2]["enrolled"])
3 people; Arianna True

Four names, one letter apart: load/dump work on a file, loads/dumps on a string — the s stands for string. Compare with the word-length table: there we wrote the format ourselves, line by line; here one call writes it and one call reads it back, structure included.

Where this comes from in real life: files like this one, and web services that answer in JSON (Lecture 10).

JSON in the lab: BIDS sidecars

BIDS (Brain Imaging Data Structure) is the standard way to organise MRI, EEG and MEG datasets. Next to every recording sits a small JSON file with how it was acquired:

{
  "TaskName": "rest",
  "Manufacturer": "Siemens",
  "MagneticFieldStrength": 3,
  "RepetitionTime": 2.0,
  "EchoTime": 0.03,
  "FlipAngle": 78,
  "SliceTiming": [0.0, 1.0, 0.2, 1.2, 0.4,
                  1.4, 0.6, 1.6, 0.8, 1.8]
}
import json

path = "resources/sub-01_task-rest_bold.json"
with open(path, "r", encoding="utf-8") as f:
    meta = json.load(f)

tr = meta["RepetitionTime"]                # seconds
print(meta["TaskName"], "at", meta["MagneticFieldStrength"], "T")
print(len(meta["SliceTiming"]), "slices, TR", tr, "s")
print("300 volumes =", 300 * tr / 60, "minutes")
rest at 3 T
10 slices, TR 2.0 s
300 volumes = 10.0 minutes

No splitting, no int(...): one json.load and the acquisition parameters are a dictionary, numbers already numbers, the slice times already a list.

The command line

Input before the program starts

input() asks while the program runs. Often it is handier to give the values when you start it, from the terminal of Lecture 1. Everything after the script’s name is an argument, and the argparse module collects them:

# echo.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("text", help="what to print back")
args = parser.parse_args()

print(args.text)
(intro2python) $ python echo.py "life is beautiful"
life is beautiful

Three steps: make a parser, tell it which arguments to expect, let it read them. Each one then waits for you in args, under the name you gave it: args.text.

The quotes matter

The terminal cuts the line at the spaces. Predict both:

(intro2python) $ python echo.py life is beautiful
usage: echo.py [-h] text
echo.py: error: unrecognized arguments: is beautiful
(intro2python) $ python echo.py
usage: echo.py [-h] text
echo.py: error: the following arguments are required: text

Without quotes, life is beautiful is three arguments, and echo.py expects one. With no argument at all, parse_args() stops the program before the lines that use the arguments, and says what was missing — you got that message for free.

Everything arrives as text

Like input(), the command line hands you strings:

# repeat.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("text")
parser.add_argument("times")
args = parser.parse_args()

print(args.text * args.times)
(intro2python) $ python repeat.py ha 3
TypeError: can't multiply sequence by non-int of type 'str'

args.times is the text "3", a string — and "ha" * "3" is the TypeError of Lecture 2’s "2" + 2.

Tell argparse the type

Give the argument a type, and argparse converts for you — and complains for you:

# repeat.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("text")
parser.add_argument("times", type=int)      # convert with int(...)
args = parser.parse_args()

print(args.text * args.times)
(intro2python) $ python repeat.py ha 3
hahaha
(intro2python) $ python repeat.py ha three
usage: repeat.py [-h] text times
repeat.py: error: argument times: invalid int value: 'three'

Optional arguments

A name starting with -- makes an argument optional:

# shout.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("text", help="the text to repeat")
parser.add_argument("--times", type=int, default=1, help="how many times")
parser.add_argument("--loud", action="store_true", help="use capital letters")
args = parser.parse_args()

text = args.text
if args.loud:
    text = text.upper()
for i in range(args.times):
    print(text)
  • --times — takes a value; if it is missing, default=1.
  • --loud — takes no value: store_true makes it True if present, False if not. A switch.

Running shout.py

Predict each one, then click:

(intro2python) $ python shout.py ciao
ciao
(intro2python) $ python shout.py --times 2 --loud ciao
CIAO
CIAO
(intro2python) $ python shout.py ciao --loud --times 3
CIAO
CIAO
CIAO

The optional arguments can go anywhere on the line, in any order: argparse recognises them by their -- name. The plain ones are matched by position.

-h for free

Every help="..." you wrote becomes documentation:

(intro2python) $ python shout.py -h
usage: shout.py [-h] [--times TIMES] [--loud] text

positional arguments:
  text           the text to repeat

options:
  -h, --help     show this help message and exit
  --times TIMES  how many times
  --loud         use capital letters

Write the real work as a function and test it in a notebook, where it is easy to try things. The script only reads the arguments and calls it. That way the part that can go wrong is never the part you cannot test.

What to take away

  1. with open(name, mode, encoding="utf-8") as f: — always with, always the encoding.
  2. "w" empties the file first, "a" adds to the end; write adds no \n.
  3. Lines read from a file end with \n — .strip() them.
  4. Read from resources/, write to output/. FileNotFoundError usually means the wrong folder.
  5. try / except SomeError: for the errors you can see coming — always named.
  6. JSON: json.dump / json.load; command line: argparse, type=int.

Try it now

What is in the file?

Write down the exact content of log.txt — characters and line breaks — before the click.

with open("output/log.txt", "w", encoding="utf-8") as f:
    f.write("one")
    f.write("two\n")

with open("output/log.txt", "a", encoding="utf-8") as f:
    f.write("three\n")

with open("output/log.txt", "r", encoding="utf-8") as f:
    print(repr(f.read()))
'onetwo\nthree\n'

'onetwo\nthree\n' — two lines. write added no newline after one, so two is glued to it; "a" then added three at the end instead of emptying the file.

Which error? (1/2)

Each snippet stops the machine. Name the error, then click.

with open("resources/no_such_file.txt", "r", encoding="utf-8") as f:
    print(f.read())
FileNotFoundError: [Errno 2] No such file or directory: 'resources/no_such_file.txt'
pages = int("3.5")
ValueError: invalid literal for int() with base 10: '3.5'

FileNotFoundError — nothing by that name in resources/ · ValueError — "3.5" is a string, but not of a whole number.

Which error? (2/2)

Two more, both writing to a file:

with open("output/log.txt", "w", encoding="utf-8") as f:
    f.write(42)
TypeError: write() argument must be str, not int
with open("output/log.txt", "w", encoding="utf-8") as f:
    f.write("hi\n")
f.write("again\n")
ValueError: I/O operation on closed file.

TypeError — write wants a string · ValueError again — the last write is outside the block, and the file is already closed.

Count the lines

The left cell writes output/notes.txt; then what does each program print?

a
b
c
with open("output/notes.txt", "w", encoding="utf-8") as f:
    f.write("a\nb\nc\n")

count = 0
with open("output/notes.txt", encoding="utf-8") as f:
    for line in f:
        count += 1
    for line in f:
        count += 1
print(count)
3
total = 0
with open("output/notes.txt", encoding="utf-8") as f:
    for line in f:
        total += len(line)
print(total)
6

3: the first loop moved the file’s finger to the end, so the second loop has nothing to read. 6: every line is a letter and its \n.

Exercises

Exercise 1 — Sum to N

Write sum_to_n.py. It asks the user for a whole number n and prints the sum 1 + 2 + ... + n.

If they type something that is not a whole number, do not crash: say so and ask again, until the answer is good. Run it in your terminal:

(intro2python) $ python sum_to_n.py
A whole number: five
‘five’ is not a whole number, try again.
A whole number: 5
1 + … + 5 = 15

Exercise 1 — solution

# sum_to_n.py
while True:
    raw = input("A whole number: ")
    try:
        n = int(raw)
        break
    except ValueError:
        print(repr(raw), "is not a whole number, try again.")

total = 0
for i in range(1, n + 1):
    total += i
print(f"1 + ... + {n} = {total}")
(intro2python) $ python sum_to_n.py
A whole number: five
'five' is not a whole number, try again.
A whole number: 5.0
'5.0' is not a whole number, try again.
A whole number: 5
1 + ... + 5 = 15

"5.0" is refused too: it is a number, but not the text of a whole one.

Exercise 2 — Write then read

Write a program that:

  1. creates output/notes.txt and writes three lines of your choice to it;
  2. opens it again and prints each line with its number in front:

1: first line
2: second line
3: third line

Use with for both steps. No blank lines between them.

Exercise 2 — solution

with open("output/notes.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")
    f.write("second line\n")
    f.write("third line\n")

number = 0
with open("output/notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        number += 1
        print(f"{number}: {line.strip()}")
1: first line
2: second line
3: third line

The counter is the Lecture 4 accumulator, and .strip() is what keeps the blank lines away.

Exercise 3 — The book, and only the book

Download Alice in Wonderland from Project Gutenberg as resources/alice.txt.

  1. Print the first 20 lines of the book itself — after the START marker — without an extra blank line after each one.
  2. Print how many lines the book has, without the licence.
  3. Print how many of those lines are empty.

Use read_book from the slides.

Exercise 3 — solution

book = read_book("resources/mini_alice.txt")   # real file: "resources/alice.txt"

for line in book[:20]:
    print(line)

empty = 0
for line in book:
    if line == "":
        empty += 1
print(len(book), "lines,", empty, "empty")
CHAPTER I.
Down the Rabbit-Hole

Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into
the book her sister was reading, but it had no pictures or
conversations in it, “and what is the use of a book,” thought Alice
“without pictures or conversations?”
8 lines, 1 empty

read_book already strips every line, so an empty line is exactly "" — and print adds the only newline. With the real alice.txt: 3,384 lines, 890 of them empty.

Exercise 4 — Count spaces to a file

Write spaces.py, which takes a sentence and an output filename on the command line, counts the spaces in the sentence, and writes that number to the file:

(intro2python) $ python spaces.py “the cat sat on the mat” output/out.txt

Write count_spaces(sentence) first and test it in a notebook; then wire up argparse.

Exercise 4 — solution

# spaces.py
import argparse


def count_spaces(sentence):
    n = 0
    for ch in sentence:
        if ch == " ":
            n += 1
    return n


parser = argparse.ArgumentParser()
parser.add_argument("sentence", help="the sentence to examine")
parser.add_argument("outfile", help="where to write the count")
args = parser.parse_args()

with open(args.outfile, "w", encoding="utf-8") as f:
    f.write(f"{count_spaces(args.sentence)}\n")
(intro2python) $ python spaces.py "the cat sat on the mat" output/out.txt
output/out.txt now holds '5\n'

Exercise 5 — Word frequencies to JSON

  1. Read the words of resources/alice.txt (read_book, then split), lower-case them and take punctuation off both ends with .strip(".,;:!?()\"'“”‘’-—") — \" is a " inside a string that is itself written between ".
  2. Count them with word_frequency from Lecture 5 — or a version of it that takes a list of words.
  3. Save the dictionary to output/alice_counts.json, then load it back in a separate step and print how many times alice appears.

Exercise 5 — solution

import json

def word_frequency(words):
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return freq

words = []
for line in read_book("resources/mini_alice.txt"):   # real: "resources/alice.txt"
    for w in line.split():
        w = w.lower().strip(".,;:!?()\"'“”‘’-—")
        if w != "":
            words.append(w)

with open("output/alice_counts.json", "w", encoding="utf-8") as f:
    json.dump(word_frequency(words), f, indent=2, ensure_ascii=False)

with open("output/alice_counts.json", "r", encoding="utf-8") as f:
    counts = json.load(f)
print(counts["alice"], counts["the"])
2 4

ensure_ascii=False keeps letters like è readable in the file instead of codes such as \u00e8. The if w != "" drops “words” that were only punctuation, like a lone —.

Exercise 6 — A diary on the command line

Write diary.py. Each time you run it with a sentence, it adds that sentence as a new line at the end of output/diary.txt; with --show, it prints the whole diary instead, numbered:

(intro2python) $ python diary.py “Learnt about files”
(intro2python) $ python diary.py “Learnt about JSON”
(intro2python) $ python diary.py –show
1: Learnt about files
2: Learnt about JSON

The sentence must be optional, so it cannot be a plain positional argument: look up nargs="?". What happens with --show on the very first run, before diary.txt exists?

Exercise 6 — solution

# diary.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("entry", nargs="?", help="the line to add")
parser.add_argument("--show", action="store_true", help="print the diary")
args = parser.parse_args()

if args.show:
    try:
        with open("output/diary.txt", "r", encoding="utf-8") as f:
            number = 0
            for line in f:
                number += 1
                print(f"{number}: {line.strip()}")
    except FileNotFoundError:
        print("The diary is empty.")
elif args.entry is not None:
    with open("output/diary.txt", "a", encoding="utf-8") as f:
        f.write(args.entry + "\n")
else:
    print("Nothing to do: give a sentence, or --show.")

Exercise 6 — solution, run

(intro2python) $ python diary.py --show
The diary is empty.
(intro2python) $ python diary.py "Learnt about files"
(intro2python) $ python diary.py "Learnt about JSON"
(intro2python) $ python diary.py --show
1: Learnt about files
2: Learnt about JSON
(intro2python) $ python diary.py
Nothing to do: give a sentence, or --show.

"a" creates the file the first time and adds to it ever after. nargs="?" means “zero or one”: when it is missing, args.entry is None, and is not None is the opposite of Lecture 3’s is None. Reading a file that does not exist yet is a FileNotFoundError, which here simply means no entries.

Questions?