Files and CSV data
Why this matters
Real data lives in files. Think of CSV exports from ad platforms and CRMs, documents you want a model to summarize, example prompts and replies for testing, and logs of everything your app sent to a model. Before you can analyze, embed or train on any of it, you need to get it into Python. Then you need to write your results back out.
- Write text to a file and read it back with open() and with
- Process a file one line at a time
- Read a CSV export into rows you can calculate with, and write one
- Build file paths with pathlib
Writing and reading a file
The academy runs Python inside your browser, with its own small file system. Files you create here live in this sandbox, not on your computer. But the code is exactly what you'd run on your own machine.
Working with a file is like using a notebook: open it, read or write, then close it.
with open("notes.txt", "w") as f: f.write("Q4 plan\n") f.write("Raise search budget\n") f.write("Test new subject lines\n") with open("notes.txt") as f: contents = f.read() print(contents)
open(path, mode) opens a file and gives you a file object, here named f. The mode says what you'll do with it:
| Mode | Meaning |
|---|---|
"r" | read (the default if you leave the mode out) |
"w" | write: creates the file, or erases an existing one first |
"a" | append: adds to the end of the file |
write doesn't add line breaks for you. \n inside a string is the newline character. It marks the end of a line.
with ... as f: makes sure the file is closed when the indented block ends, even if an error happens partway through. Always open files this way. A file left open can lose data that was written but not yet saved.
Tip: add
encoding="utf-8"when you open text files on your own computer, for exampleopen("notes.txt", encoding="utf-8"). Then accents, non-English text and emoji read correctly on every system.
One line at a time
Looping over a file object gives you its lines one by one. Each line still ends with its \n, so .strip() it:
with open("subjects.txt", "w") as f: f.write("Last chance: 30% off\n") f.write("New arrivals you'll love\n") f.write("Your weekly picks\n") with open("subjects.txt") as f: for line in f: line = line.strip() print(len(line), line)
f.readlines() gives you all the lines as a list instead. Looping is better for big files, because Python only holds one line in memory at a time. A 2 GB log file is fine to loop over. It would be painful to load all at once.
Appending is how logs grow:
with open("log.txt", "w") as f: f.write("batch 1 sent\n") with open("log.txt", "a") as f: f.write("batch 2 sent\n") with open("log.txt") as f: print(f.read())