Adding to the end of a file
Opening a file with "w" always starts from an empty file. To add lines to the end of a file and keep what's already in it, open it in append mode, "a":
Ana
Bowith open("visitors.txt", "a") as file:
file.write("Cy\n")
file.write("Dee\n")
with open("visitors.txt") as file:
print(file.read())
Ana
Bo
Cy
DeeIf the file doesn't exist yet, "a" creates it, just as "w" would. So the three modes so far are:
- no mode (or
"r", for read): read a file that must exist; "w", write: start a new, empty file, wiping out any old one with that name;"a", append: add to the end of a file, creating it if needed.
A log that grows
Append mode suits files that only ever grow, such as a log: a file where a program notes what it has done. Each call of this function opens the file, adds one line and closes it again:
def log(message):
with open("log.txt", "a") as file:
file.write(message + "\n")
log("Program started")
log("Loaded 3 users")
log("Program ended")
with open("log.txt") as file:
for line in file:
print("LOG:", line.strip())
LOG: Program started
LOG: Loaded 3 users
LOG: Program endedIf you ran this program again on your own computer, the file would get three more lines below these. (On this site, every run starts in a fresh folder with only the files the task gives.) With "w" in log instead, every call would empty the file before writing its line, so even a single run would leave only the last message, Program ended.
Appending is handy, but it can only add to the end. A program that needs to change something in the middle of a file, or remove a line from it, reads the whole file, changes the data and writes all of it again with "w". The last step of this module shows how.