Originally published on my newsletter, The Path to AI FDE. Subscribe free to get each issue by email.
This is a “From Zero” issue. Yesterday you held data in lists and dictionaries. But that data vanished the moment your script ended. Today you save it to a file and read it back.
Most of an AI engineer’s day is text: cleaning it, putting it into prompts, reading it from files, and passing JSON back and forth. So today covers the three tools for that: strings, files and JSON. By the end you’ll have a script that tidies a messy, made-up shopping list and saves it as JSON.
Part A · Strings
1. f-strings put values inside text. Put an f just before the opening quote, and anything inside curly braces { } is replaced by its value. Save this as fstrings.py in your sandbox folder:
name = "Asha"
cups = 2
price = 1.5
print(f"{name} ordered {cups} cups")
print(f"Total: {cups * price}")
print(f"Price: {price:.2f}")
n = 10
text = "The cat sat on the mat."
prompt = f"Summarise this in {n} words: {text}"
print(prompt)
Run it with python3 fstrings.py (Windows: python fstrings.py):
Asha ordered 2 cups
Total: 3.0
Price: 1.50
Summarise this in 10 words: The cat sat on the mat.
The braces can hold a name or a small calculation, such as {cups * price}. Add a colon and a format after it to control how a value looks: :.2f means “a number with 2 decimal places”, so 1.5 shows as 1.50.
The last example is a toy prompt template: a fixed sentence with gaps for values. Later in the series, you’ll build prompts for AI models in exactly this way. Forget the f and Python prints the braces as they are: Asha ordered {cups} cups.
2. String methods clean up text. A method is a function that belongs to a value, called with a dot. Strings come with dozens. These five cover most cleaning jobs:
raw = " Hello, World! "
print(raw.strip())
print(raw.strip().lower())
print(raw.replace("World", "Python"))
words = "tea,milk,sugar".split(",")
print(words)
print(" + ".join(words))
print(raw)
Hello, World!
hello, world!
Hello, Python!
['tea', 'milk', 'sugar']
tea + milk + sugar
Hello, World!
-
.strip()removes spaces (and newlines) from both ends. -
.lower()makes it all lowercase, handy before comparing text..upper()does the opposite. -
.replace(old, new)swaps every match. -
.split(",")cuts a string into a list at each comma. With no argument,.split()cuts at any run of spaces. -
" + ".join(words)does the reverse: it glues a list of strings into one, with" + "between them.
You can chain methods, read left to right: raw.strip().lower() strips first, then lowercases. And notice the last line: raw still has its spaces. Strings never change. Each method hands back a new string, so keep the result: clean = raw.strip().
Part B · Files and JSON
3. with open(...) reads and writes files, and closes them for you. Here’s how to write a small file, then read it back two ways:
with open("note.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
f.write("second line\n")
with open("note.txt", encoding="utf-8") as f:
text = f.read()
print(text.splitlines())
with open("note.txt", encoding="utf-8") as f:
for line in f:
print(line.strip().upper())
['first line', 'second line']
FIRST LINE
SECOND LINE
open() takes the file name, a mode, and an encoding (point 6). The mode "w" means write, and it replaces anything already in the file. "a" adds to the end. Leave the mode out and it reads ("r"). \n is the newline character, the end of a line.
The with line opens the file and names it f. When the indented block ends, Python closes the file for you, even if an error happens halfway through. That’s why the Python tutorial recommends with: a file left open can lose writes or stay locked.
To read, f.read() gives the whole file as one string, and .splitlines() cuts it into a list of lines. Or loop over f to get one line at a time, which works even for huge files. Each line still ends with \n, which is why we strip it.
Open a file that doesn’t exist and you get:
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
4. Build paths with pathlib, and find files with glob. A path is a file’s address, like sandbox/notes/a.txt. Python’s built-in pathlib module handles paths for you:
from pathlib import Path
here = Path(__file__).parent
notes = here / "notes"
notes.mkdir(exist_ok=True)
(notes / "a.txt").write_text("apple\n", encoding="utf-8")
(notes / "b.txt").write_text("banana\n", encoding="utf-8")
(notes / "c.md").write_text("# not a txt\n", encoding="utf-8")
for p in sorted(notes.glob("*.txt")):
print(p.name, p.suffix, p.read_text(encoding="utf-8").strip())
print((notes / "a.txt").exists())
a.txt .txt apple
b.txt .txt banana
True
Line by line:
-
Path(__file__).parentis the folder this script lives in. (__file__is the script’s own path.) -
here / "notes"joins path parts with a slash. It works on Windows, macOS and Linux alike, so you never type\or/yourself. -
.mkdir(exist_ok=True)makes the folder, and doesn’t complain if it’s already there. -
.write_text()and.read_text()write or read a whole file in one line, for small files. -
.glob("*.txt")finds every file whose name matches the pattern.*means “anything”, so it findsa.txtandb.txtbut skipsc.md.sorted()puts them in a fixed order.
Why bother? Because a hard-coded path like C:\Users\asha\Desktop\notes only works on one computer. And a plain "note.txt" is looked for in whatever folder you ran the command from, so the same script can fail if you run it from somewhere else. Building paths from Path(__file__).parent works wherever the folder ends up.
5. JSON in and out with json. Yesterday you met JSON text. Python’s built-in json module converts it both ways:
import json
text = '{"name": "Asha", "cups": 2, "milk": true}'
order = json.loads(text)
print(order["cups"] + 1)
print(type(order))
order["milk"] = False
print(json.dumps(order))
print(json.dumps(order, indent=2))
3
<class 'dict'>
{"name": "Asha", "cups": 2, "milk": false}
{
"name": "Asha",
"cups": 2,
"milk": false
}
-
json.loads(text)turns JSON text into Python data: here, a dictionary you can use straight away. JSON’struebecomes Python’sTrue. -
json.dumps(data)turns Python data back into JSON text.indent=2spreads it over lines so people can read it.
The s at the end of loads and dumps stands for string. Their twins without the s, json.dump(data, f) and json.load(f), write straight to and read straight from an open file:
import json
order = {"name": "Asha", "cups": 2}
with open("order.json", "w", encoding="utf-8") as f:
json.dump(order, f, indent=2)
with open("order.json", encoding="utf-8") as f:
back = json.load(f)
print(back == order)
True
Save, then load, and you get back exactly what you saved. One gotcha: JSON needs double quotes. json.loads("{'name': 'Asha'}") fails with:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
6. Always say encoding="utf-8". Files don’t store letters. They store bytes, numbers from 0 to 255. An encoding is the table that turns characters into bytes and back. UTF-8 is the one to use: it covers every language and emoji, and it’s what the web and JSON use.
Here’s what happens when the write and the read disagree:
with open("menu.txt", "w", encoding="utf-8") as f:
f.write("café\n")
with open("menu.txt", encoding="utf-8") as f:
print(f.read().strip())
with open("menu.txt", encoding="cp1252") as f:
print(f.read().strip())
print(len("café"), len("café".encode("utf-8")))
café
café
4 5
Read with the same encoding and you get café. Read the very same bytes as cp1252, an older Windows encoding, and you get the garbled café. The last line shows why: é takes two bytes in UTF-8, so the 4-character word is 5 bytes long. With the wrong table, those two bytes turn into two wrong characters.
Why can this bite you? If you leave encoding out, Python picks a default. Before Python 3.15, that default depended on the computer’s settings, so the same script could read a file fine on a Mac and garble it on Windows. Python 3.15 changed the default to UTF-8, but you’ll meet older Pythons for years. So always write encoding="utf-8" and it doesn’t matter.
Try it (15 minutes)
- In your
sandboxfolder, create a file calledgroceries.txtwith this made-up, messy list. Type it exactly, including the extra spaces, the capitals, the blank line and the repeated milk:
Milk
EGGS
bread
milk
Tomatoes
- Next to it, create
tidy_list.py:
import json
from pathlib import Path
here = Path(__file__).parent
raw = (here / "groceries.txt").read_text(encoding="utf-8")
items = []
for line in raw.splitlines():
item = line.strip().lower()
if item and item not in items:
items.append(item)
print(f"Found {len(items)} items: {', '.join(items)}")
out = here / "groceries.json"
out.write_text(json.dumps(items, indent=2), encoding="utf-8")
back = json.loads(out.read_text(encoding="utf-8"))
print(back[0], back == items)
- Run
python3 tidy_list.py. You should see:
Found 4 items: milk, eggs, bread, tomatoes
milk True
if item skips the blank line, because an empty string counts as False. item not in items skips the second milk. Open groceries.json in VS Code to see the saved list.
- Run it from a different folder, for example
cd ..and thenpython3 sandbox/tidy_list.py. It still works, because the paths are built fromPath(__file__).parent. Now change the line toraw = Path("groceries.txt").read_text(encoding="utf-8")and run it from the parent folder again:FileNotFoundError. Change it back. - Add a line to
groceries.txt, such asCafé au lait, run the script again, and check that theésurvives the trip to JSON. (In the file,json.dumpswrites it as\u00e9unless you passensure_ascii=False. Both load back asé.)
Check your understanding: (a) What’s the difference between json.loads and json.load? (b) Why use with to open a file? (c) After s = " hi " and s.strip(), what is s?
Answer: (a) json.loads reads JSON from a string; json.load reads it from an open file. (b) It closes the file for you when the block ends, even if an error happens. (c) Still " hi ". Strings never change; s.strip() returns a new string, so write s = s.strip().
Common beginner mistakes
- Opening files without
with, and forgetting to close them. - Hard-coding a path that only exists on your computer. Build it with
pathlibfromPath(__file__).parent. - Leaving out
encoding="utf-8", then getting garbled text, or aUnicodeDecodeError, on another computer. - Calling
s.strip()and expectingsto change. Keep the result. - Opening a file with
"w"when you meant to add to it."w"wipes it first;"a"appends. - Writing JSON by hand with single quotes. Let
json.dumpswrite it.
Takeaway
f-strings put values into text. String methods (.strip(), .lower(), .split(), .replace(), .join()) return new strings, so keep the result. with open(path, encoding="utf-8") reads and writes files and closes them for you. pathlib builds paths that work on any computer, and glob finds files. json.loads/json.dumps convert JSON text, and json.load/json.dump work with files.
Where this fits in my roadmap: this is part of my on-ramp, the Python basics everything else sits on. An AI app is mostly text plumbing: read files, clean the text, drop it into a prompt template, and parse JSON that comes back. Tomorrow: errors and exceptions, so that when a file is missing or the JSON is broken, your script says why instead of just crashing.
Over to you: what’s the messiest text file you’ve had to clean by hand? Reply with one line of it (nothing private), and the string method you’d use first.
Sources
- Python tutorial, “Input and Output”, Formatted String Literals (f-strings, format specifiers such as
:.2f). https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals - Python docs, “Built-in Types”, String Methods (
str.strip,str.lower,str.split,str.replace,str.join; strings are immutable). https://docs.python.org/3/builtins/stdtypes.html#string-methods - Python tutorial, “Input and Output”, Reading and Writing Files (modes
"r","w","a"; “It is good practice to use thewithkeyword”; specifyingencoding="utf-8") and Methods of File Objects. https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files - Python docs, “pathlib” (
Path, the/operator,Path.glob,Path.read_text,Path.write_text,Path.mkdir,Path.exists). https://docs.python.org/3/library/pathlib.html - Python docs, “json” (
json.loads,json.dumps,json.load,json.dump,indent,ensure_ascii,JSONDecodeError). https://docs.python.org/3/library/json.html - Python docs, “Built-in Functions”,
open()(the default encoding; “Changed in version 3.15: UTF-8 is now the default encoding”). https://docs.python.org/3/builtins/functions.html#open - PEP 686, “Make UTF-8 mode default” (status Final; the reason for the change). https://peps.python.org/pep-0686/
- Python HOWTO, “Unicode HOWTO” (characters, bytes and encodings). https://docs.python.org/3/howto/unicode.html
All examples are made up and were run with Python 3.13 on Nov 2, 2026. Error messages are from Python 3.13; other versions word some of them differently. Sources checked Nov 2, 2026.
Free: the 5-page roadmap from Novice to AI FDE.
If this was useful, subscribe to The Path to AI FDE for the next issue.







Top comments (0)