Read Cards from a Notes File

So far every value a program used was typed into the code or into the terminal. Most real data lives in files instead, and a program that can read a file can work with any amount of it, changed whenever you like, without touching the code. Reading a file takes four small ideas: using code that comes with Python, naming where the file is, reading its text, and cutting that text into lines.

Ready-made code: modules and import

Opening a file, finding it on the disk and turning what is stored there into letters is a lot of careful work. You do not have to write it yourself, because Python comes with that code already written.

That code is kept in modules. A module is a file of Python code, full of definitions such as functions, that other programs can use. The modules that are installed together with Python itself are called the standard library. There are many of them: one for dates, one for random numbers, one for working with files and folders, and many more. You do not download them; they are there as soon as Python is.

A program cannot use a module straight away, though. It first asks for it with an import line, usually at the very top of the file.

The module for file paths is called pathlib, and it holds a tool called Path. There are two ways to ask for it:

Two ways to import
# Bring in the whole module: reach its parts with a dot.
import pathlib
p = pathlib.Path("groceries.txt")

# Bring in one name from the module: use it directly.
from pathlib import Path
p = Path("groceries.txt")

The first form gives the program the name pathlib, and everything inside the module is reached through it with a dot, the same dot you already use for string methods. The second form, from ... import ..., takes just the names you list and puts them straight into your program, so you can write Path on its own. Both do the same work; the second is shorter when you use one name often. Python runs a module's code only the first time it is imported, so importing it again later costs nothing.

True or false?

After the line import pathlib, a program can write Path("a.txt") on its own.

False. import pathlib brings in only the name pathlib. The tool is reached as pathlib.Path. To write Path alone, use from pathlib import Path.

A module from the standard library has to be downloaded before a program can import it.

False. The standard library is installed together with Python. An import line is all it takes.

An import line is usually placed at the top of the file, before the code that uses the module.

True. A name has to exist before it is used, and Python reads the file from the top, so imports come first.

Paths: the address of a file

Files on a computer sit inside folders, and folders sit inside other folders. To read a file, a program has to say exactly which one it means. The way to say it is a path: the address of a file or a folder, written as the names of the folders you pass through, one after another, ending with the file's name.

  • shop terminal here
  • app.py
  • lists
  • groceries.txt
  • hardware.txt
  • shop to app.py
  • shop to lists
  • lists to groceries.txt
  • lists to hardware.txt

In this folder tree, the file groceries.txt sits in the folder lists. Starting from the folder shop, its path is lists/groceries.txt: first the folder, then the file. Windows writes the same path with a backslash, lists\groceries.txt.

Because the separator differs from one system to another, it is safer not to type it at all. A Path is built from the parts, and Python joins them with the right separator for the computer the program runs on. You can pass the parts to Path, or join them with the / sign, which on paths means "go one level further in", not division:

from pathlib import Path

folder = Path("lists")
file = folder / "groceries.txt"
same_file = Path("lists", "groceries.txt")

print(file)       # lists/groceries.txt  (lists\groceries.txt on Windows)
print(file.name)  # groceries.txt

A path value is only an address. Building one does not open the file or even check that it is there; file.exists() asks that question and gives back True or False.

Where a relative path starts

The path lists/groceries.txt does not start at the top of the disk. It is a relative path: it starts from one particular folder. That folder is the one the program is running in, and it has a name of its own, the current working directory. When you start a program from the terminal, that is the folder the terminal is in at that moment, not the folder where the .py file happens to be saved.

If the terminal is in shop, the path leads to the file. If you first move the terminal into lists and start the same program from there, Python looks for lists/lists/groceries.txt, which does not exist, and the program stops with a FileNotFoundError. When a file that is clearly there cannot be found, the first thing to check is the folder the program was started in. Path.cwd() gives back that folder, so printing it shows where relative paths begin.

True or false?

A relative path is looked up starting from the folder where the .py file is saved.

False. It starts from the current working directory: the folder the program was started in, which is where the terminal was.

In Path("lists") / "groceries.txt", the / joins the two parts into one longer path.

True. On paths, / means one level further in. Nothing is divided, and Python puts in the right separator for the system.

Writing Path("lists/groceries.txt") checks that the file exists.

False. Building a path only writes down an address. Use exists() to ask whether something is there.

Reading the whole text of a file

Once a program has a path, one method call reads the file: read_text. It opens the file, reads everything in it, closes the file again, and gives back the whole content as one string.

from pathlib import Path

path = Path("lists") / "groceries.txt"
text = path.read_text(encoding="utf-8")
print(text)

The string holds the file exactly as it was written, including the line breaks between the lines. A line break is a character of its own, written \n in Python code, so a file with three short lines comes back as a single string such as "milk\nbread\neggs\n".

Why the encoding is named

A file on a disk does not store letters. It stores numbers, called bytes, and an encoding is the rule that says which bytes stand for which letter. Plain English letters are stored the same way by almost every encoding, but letters such as é, ü or ñ are not. Today the usual encoding for text files is UTF-8, which can store the letters of every language.

If a program reads a file with a different rule from the one it was saved with, the letters come out wrong. Here is one word saved as UTF-8 and read back with two rules:

StepResult
Word saved in the filecrème
Bytes UTF-8 stores for èC3 A8 (two bytes)
Read back as UTF-8crème
Read back with an older Windows rule (cp1252)crème

The older rule reads each of the two bytes as a letter of its own, so one letter turns into two wrong ones. Writing encoding="utf-8" in the call tells Python which rule to use, so every letter is read as it was written, on every computer.

Without that argument, Python picks a rule by itself. Since Python 3.15 that default is UTF-8, but older versions used the computer's own setting, which on Windows is often not UTF-8. Python's own documentation still recommends always naming the encoding, and doing so makes the result the same whichever version runs the program.

True or false?

After read_text, the program must close the file itself.

False. read_text opens the file, reads it and closes it again before it gives the string back.

read_text gives back one string, with the line breaks of the file still inside it.

True. The whole file arrives as a single string; each line break is a \n character in it.

A file containing only English letters reads the same with UTF-8 and with most other encodings.

True. Plain English letters are stored with the same bytes in almost every encoding. The differences show up in letters such as é, ü or ñ.

Cutting the text into lines

One long string is hard to work with. A program that wants to handle a file one line at a time needs a list with one string per line, and the string method splitlines makes exactly that. It cuts the text at every line break and leaves the line breaks themselves out.

text = "milk\nbread\n\neggs\n"

print(text.splitlines())   # ['milk', 'bread', '', 'eggs']
print(text.split("\n"))    # ['milk', 'bread', '', 'eggs', '']

You could also split at the line break character with split("\n"), but the two differ at the end. A text file almost always ends with a line break, and split sees one more piece after it: an empty string. splitlines does not add that extra piece, and it also understands the line breaks Windows uses, so it is the method made for this job.

Now look at the third item in both lists. The file had a blank line between bread and eggs, and a blank line is still a line: it becomes the empty string ''. Blank lines are common in files that people write by hand, so a program usually leaves them out. It walks through the lines and collects only the ones that hold something:

from pathlib import Path

text = Path("lists", "groceries.txt").read_text(encoding="utf-8")

items = []
for line in text.splitlines():
    if line.strip():
        items.append(line.strip())

print(items)   # ['milk', 'bread', 'eggs']

The test works because of two things you already know. strip() gives back a copy without spaces at the ends, so a line that holds only spaces becomes '' too. And an empty string counts as False in a condition, just as an empty list does. So if line.strip(): is true only for lines with real text in them, and those are the ones that reach the list. The result is a plain list of strings that the rest of the program can loop over, index or count.

True or false?

splitlines leaves blank lines out of the list it gives back.

False. A blank line becomes an empty string in the list. Only the extra piece after the final line break is left out.

For the text "a\nb\n", split("\n") gives one more item than splitlines().

True. split("\n") gives ['a', 'b', ''] with an empty string after the last break; splitlines() gives ['a', 'b'].

A line that holds only two spaces passes the test if line.strip():

False. strip() turns it into the empty string, which counts as False, so the line is left out.