Python for AIPython 3.10+ · Pydantic 2.12
Dashboard
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
34 small wins to finish your pathNext lesson →

Reading and writing files

open() is the built-in function that opens a file for reading or writing, and a with block closes the file for you when it ends.

Last updated: 30 Sep, 2026 · Python 3.14

A program's variables are gone when it ends. Writing to a file keeps what the program found, and reading one gives it data someone else prepared.

Syntax:

python
with open("name.txt", "w") as f:    # "w" write, "a" append, no mode reads
    f.write("text\n")

Writing a file and reading it back

Example
with open("notes.txt", "w") as f:
    f.write("Ticket 1: refund sent\n")
    f.write("Ticket 2: waiting on the courier\n")

with open("notes.txt") as f:
    print(f.read())

open takes a file name and a mode. "w" means write, and creates the file or empties an existing one. With no mode, open reads.

with closes the file when its block ends, even if something fails inside. write does not add a new line for you, which is why each line ends with \n.

Reading line by line

Example
with open("notes.txt") as f:
    for line in f:
        print(line.strip())

Looping over an open file gives one line at a time, with its \n still attached. strip from Strings removes it; without it, print adds a second line break and the output gains blank lines.

Appending without erasing

Example
with open("notes.txt", "a") as f:
    f.write("Ticket 3: password reset link sent\n")

with open("notes.txt") as f:
    print(f.read())

"a" is append: new text goes at the end and what was there stays. Run it twice and Ticket 3 appears twice, because "a" always adds.

Opening a file that does not exist

Example
with open("tickets.txt") as f:
    print(f.read())

The file name is relative to the folder the program runs from. A wrong name or a wrong folder gives the same FileNotFoundError.

"w" vs "a"

"w""a"
File existsEmptied firstKept; new text goes at the end
File missingCreatedCreated
Use it forWriting a fresh resultAdding to a log

Where files show up in AI code

  • Saving a model's answers so a long run is not lost when the program ends.
  • Reading documents, prompts or test cases prepared by someone else.
  • Appending one line per call to a log file.
Watch out. "w" empties the file the moment it opens, before you write anything. Opening a file of saved results with "w" by mistake loses them.
Try it yourself
  • Change "a" to "w" in the append example and see what happens to the first two lines.
  • Count the lines in notes.txt with a loop and a counter.
  • Write each item of a list to its own line.

Little by little, you're building something great.