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:
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
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())Ticket 1: refund sent Ticket 2: waiting on the courier
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
with open("notes.txt") as f:
for line in f:
print(line.strip())Ticket 1: refund sent Ticket 2: waiting on the courier
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
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())Ticket 1: refund sent Ticket 2: waiting on the courier Ticket 3: password reset link sent
"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
with open("tickets.txt") as f:
print(f.read())Traceback (most recent call last):
File "main.py", line 1, in <module>
with open("tickets.txt") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'tickets.txt'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 exists | Emptied first | Kept; new text goes at the end |
| File missing | Created | Created |
| Use it for | Writing a fresh result | Adding 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.
"w" empties the file the moment it opens, before you write anything. Opening a file of saved results with "w" by mistake loses them.Related
- Previous: import and modules
- Next: JSON
- Reference: Reading and Writing Files in the Python tutorial
- Change
"a"to"w"in the append example and see what happens to the first two lines. - Count the lines in
notes.txtwith a loop and a counter. - Write each item of a list to its own line.
Little by little, you're building something great.