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

Files: reading and writing text

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.

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.

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 lesson 3 removes it; without it, print adds a second line break and the output gains blank lines.

Adding 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.

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.

Try it yourself
  • Change "a" to "w" in the last 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.

Every expert started right here.