Handling Files
Sometimes you want your program to remember data even after it closes — like a list of scores or entries a user has added. That’s where files come in. Python makes it easy to read data from a file and write data to one.
Opening a file
Use the open() function to open a file. You pass it the filename and a mode that tells Python what you want to do with it:
| Mode | What it does |
|---|---|
"r" | Read — open an existing file to read from it |
"w" | Write — create or overwrite a file |
"a" | Append — add to the end of an existing file (or create it) |
my_file = open("scores.txt", "r")This opens scores.txt in read mode and stores the result in a variable. You’ll use that variable to read or write.
Reading from a file
The most common way to read is to loop over the file line by line:
my_file = open("scores.txt", "r")
for line in my_file:
print(line.strip())
my_file.close()Each pass through the loop gives you the next line as a string. .strip() removes the newline character at the end — you’ll almost always want that.
If you need the whole file at once as a single string, use read():
my_file = open("scores.txt", "r")
content = my_file.read()
print(content)
my_file.close()If you want all the lines as a list, use readlines():
my_file = open("scores.txt", "r")
lines = my_file.readlines() # returns ["line 1\n", "line 2\n", ...]
my_file.close()For most projects, the for line in file loop is all you need.
Writing to a file
Open in write mode and use the write() method:
my_file = open("scores.txt", "w")
my_file.write("Alice: 95\n")
my_file.write("Bob: 88\n")
my_file.close()Opening a file with "w" wipes out anything already in it. If you want to add to the end without deleting what’s there, use "a" (append) instead.
my_file = open("scores.txt", "a")
my_file.write("Carol: 92\n")
my_file.close()Closing a file
Always close the file when you’re done with close(). This saves everything to disk and frees up resources — think of it like saving and closing a document.
my_file.close()Using with (recommended)
A cleaner way to work with files is the with block. It closes the file automatically when the block ends, even if something goes wrong:
with open("scores.txt", "r") as my_file:
for line in my_file:
print(line.strip())You don’t need to call close() yourself. Once the indented block finishes, Python handles it. This is the pattern you’ll see most often in real code.