Files, JSON, and the command line
October 7, 2026
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:
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.
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.
A program cannot touch the disk directly. It asks for a connection to one file, uses it, and hands it back:
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 printPredict what ends up in the file:
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.
with blockForget 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:
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" addsOpening 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.
read()read() hands back the whole file as one string, newlines included:
first line
second line
third line
'first line\nsecond line\nthird line\n'
34 characters
From here it is an ordinary string, and Lecture 3 applies:
['first line', 'second line', 'third line']
FIRST LINE
SECOND LINE
THIRD LINE
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
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.
\nprint 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
'first line\n' 11
'second line\n' 12
'third line\n' 11
\nOne 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.
first line
second line
third line
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.
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
['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.
first line
second line
third line
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.
open("output/notes.txt") does not search your computer. It starts from one folder: the folder the program was started from, its working directory.
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:
C:\Users\sara\intro2python
intro2python/. The working directory is then the folder that contains resources/ and output/.intro2python/ too, next to your scripts.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.
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: garbageCittà: Trento — perché no?
Città : Trento — perché no?
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.
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.
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.
ValueError: invalid literal for int() with base 10: 'ten'
try / except says: try this; if this particular error happens, do that instead of stopping.
that was not a whole number
the program carries on
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:
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.
The validation loop of Lecture 4 crashed if the user typed a word. With try it keeps asking instead:
(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
The same idea with a file: the book is not downloaded yet, and the program says so instead of crashing.
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.
An except with no name catches everything — including your own typos:
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.
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.
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...
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', '']
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.
How many words have 1 letter, 2 letters, 3…? Count only the letters, so that book,” has length 4:
{7: 6, 1: 2, 4: 8, 3: 16, 10: 1, 5: 4, 9: 1, 2: 16, 6: 4, 8: 2, 13: 2}
Save the table to a file, one length per line, shortest first:
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.
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.
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 |
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:
Sara is enrolled
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).
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.
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:
(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 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.
Like input(), the command line hands you strings:
(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.
argparse the typeGive the argument a type, and argparse converts for you — and complains for you:
(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'
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.shout.pyPredict 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 freeEvery 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.
with open(name, mode, encoding="utf-8") as f: — always with, always the encoding."w" empties the file first, "a" adds to the end; write adds no \n.\n — .strip() them.resources/, write to output/. FileNotFoundError usually means the wrong folder.try / except SomeError: for the errors you can see coming — always named.json.dump / json.load; command line: argparse, type=int.Write down the exact content of log.txt — characters and line breaks — before the click.
'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.
Each snippet stops the machine. Name the error, then click.
FileNotFoundError: [Errno 2] No such file or directory: 'resources/no_such_file.txt'
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.
Two more, both writing to a file:
TypeError: write() argument must be str, not int
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.
The left cell writes output/notes.txt; then what does each program print?
a
b
c
3
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.
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
(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.
Write a program that:
output/notes.txt and writes three lines of your choice to it;1: first line
2: second line
3: third line
Use with for both steps. No blank lines between them.
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.
Download Alice in Wonderland from Project Gutenberg as resources/alice.txt.
Use read_book from the slides.
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.
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.
# 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'
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 ".word_frequency from Lecture 5 — or a version of it that takes a list of words.output/alice_counts.json, then load it back in a separate step and print how many times alice appears.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 —.
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?
# 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.")(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.
Intro to Programming (Python) · Fall 2026