Python Arena
Step 2 of 4

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":

The file visitors.txt
Ana
Bo
with open("visitors.txt", "a") as file:
    file.write("Cy\n")
    file.write("Dee\n")

with open("visitors.txt") as file:
    print(file.read())
Output
Ana
Bo
Cy
Dee

If 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())
Output
LOG: Program started
LOG: Loaded 3 users
LOG: Program ended

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

Your task

Challenge 1 of 3

The file shopping.txt already has a shopping list in it. Fill in the blank so the program adds bananas to the end of the list and keeps the items that are already there. With this file

eggs
flour

the program leaves this in shopping.txt:

eggs
flour
bananas

Challenge 2

Write a function add_note(note) that adds the note as a new line to the end of the file notes.txt. Whatever was in the file before stays there. If the file doesn't exist yet, the function creates it.

For example, if notes.txt has

Buy stamps

then after add_note("Water the plants") it has:

Buy stamps
Water the plants

Challenge 3

The file scores.csv holds the high scores of a game, one name;score line per game played. Write a program that asks for a player's name and score, adds them as a new line to the end of the file, and then prints every line of the file, numbered, as in the example.

If scores.csv has

Ana;950
Bo;720

a run looks like this:

Name: Cleo
Score: 870
1. Ana: 950
2. Bo: 720
3. Cleo: 870

and the file ends up with three lines, the last one Cleo;870.