Variables vanish when a program ends. To keep data, programs write files, and to work on data from elsewhere they read them. open(path, mode) opens a file; the mode is "r" to read (the default), "w" to write (which empties the file first) or "a" to append to the end.
Always open files with with. It closes the file for you when the block ends, even if an error happens, which matters because unclosed files can lose data. Pass encoding="utf-8" so accented letters and emoji are read the same on every computer.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
f.write("second line\n")
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())
That prints the two lines. Looping over a file gives one line at a time, each still ending in its \n line break, which is why strip() is there. f.read() gives the whole file as one string instead. If the file doesn't exist, reading raises FileNotFoundError.
A path says where a file is. notes.txt on its own means the folder the program was started from. The pathlib module handles paths properly on every operating system: Path("data") / "notes.txt" joins folder and file name, and a Path can read and write small files in one call.
(tempfile.mkdtemp() makes a new empty folder for scratch files, so the example doesn't touch your own. The import lines load extra tools; the next lesson covers them.)
Two formats cover most data files. CSV (comma-separated values) is a table as text, one row per line, which spreadsheets open and save. The csv module reads it properly, including commas inside quoted values. DictReader gives each row as a dict keyed by the header line.
import csv, io
text = "name,city\nAna,Lima\nBen,\"Austin, TX\"\n"
for row in csv.DictReader(io.StringIO(text)):
print(row["name"], "|", row["city"])
Prints
Ana | Lima
Ben | Austin, TX
(io.StringIO makes a string act like an open file, handy for examples and tests; with a real file you'd pass the f from open(), opened with newline="" as the csv docs advise.) JSON stores nested data, dicts and lists, as text, and is what most web services send. json.dumps() turns Python data into a JSON string and json.loads() turns it back; json.dump(data, f) and json.load(f) do the same with a file.
import json
data = {"name": "Ana", "scores": [9, 7], "member": True}
text = json.dumps(data)
print(text)
back = json.loads(text)
print(back["scores"][0])