Sometimes you will need to write data to a file.

The process of writing to a file is always the same. The only thing that changes is what file you are writing to and what you write to the file.

Below are the key steps to the process:

  • Open a connection to a file in append mode.
  • Write the information you want to a file
  • Close the connection to the file

Write modes

When you read from a file you would use the cost file = open("filename.csv","r"). The r stands for read. It would make sense that when you write to a file you use w instead, but you don’t. w does stand for write mode, but it means overwrite. Therefore each time you write to the file it will overwrite what is in there already.

Therefore when you want to open a connection to a file to write to, you use append or a mode. Append means add. It will add to the file rather than overwrite what is already there.

writefile = open("filename.csv", "a")

NOTE: you can call the variable writefile whatever you want.

Worked example - File Writing - Christmas List

Imagine a program that when run asks the user to enter a gift they want for Christmas, how much it costs and the priority of how much they want it.

Step 1 - Getting the information to write to the file

gift = input("Enter the gift you would like: ")
cost = input("Enter the cost of the gift: ")
priority = input("Enter the priority of the gift (1=low, 5=high): ")

Before you can write to the file you need to get the information from the user that you want to add to the file.

Step 2 - Creating a connection to the file

writefile = open("filename.csv", "a")

This code will create a connection to the file filename.csv in a mode which stands for append. It can then be referred to as the variable name which is writefile

Step 3 - Write the information to the file 

As you are writing to a csv file you need to separate each piece of data that you want to add with a comma.

writefile.write(gift + "," + cost + "," + priority + "\n")

NOTE: the at the end means new line, this means next time you write to the file it will add the new set of information on a new line.

Step 4 - Closing the connection 

Once you have written to the file you need to close the connection to the file. This means it can be used by other parts of the program if needed.

writefile.close()

The final code looks like this:

gift = input("Enter the gift you would like: ")
cost = input("Enter the cost of the gift: ")
priority = input("Enter the priority of the gift (1=low, 5=high): ")
writefile = open("christmaslist.csv","a")
writefile.write(gift + "," + cost + "," + priority + "\n")
writefile.close()
print("Gift added to the file")

The finished program looks like this when run:

The file created looks like this:

Example program 1

Deciding whether to write to a file

Sometimes before you add information to a file, you might need to check if it meets certain requirements. This will require building selection (IF) into your code.

At the moment the program above will always write the information entered to a file. Consider this new requirement:

Santa is running out of money, it should only write to the file gifts that cost less than £150, otherwise say they cost too much.

How to do this:

After the information has been entered create an if that checks if the if the cost is less than £150.

gift = input("Enter the gift you would like: ")
cost = input("Enter the cost of the gift: ")
priority = input("Enter the priority of the gift (1=low, 5=high): ")
if float(cost) < 150:

if the cost is less than £150, then the lines of code that write to a file should be run.

if float(cost) < 150:
    writefile = open("christmaslist.csv","a")
    writefile.write(gift + "," + cost + "," + priority + "\n")
    writefile.close()
    print("Gift added to the file")

if the cost is not less than £150, add an else and add code to say that the gift is too expensive.

else:
    print("That gift is too expensive, Santa doesn't have enough money")

The final code now looks like this:

gift = input("Enter the gift you would like: ")
cost = input("Enter the cost of the gift: ")
priority = input("Enter the priority of the gift (1=low, 5=high): ")
if float(cost) < 150: #new code
    writefile = open("christmaslist.csv","a")
    writefile.write(gift + "," + cost + "," + priority + "\n")
    writefile.close()
    print("Gift added to the file")
else: #new code
    print("That gift is too expensive, Santa doesn't have enough money") #new code

Example program 2

Checking if data exists in a file before adding new data

Sometimes you will need to create a program that reads through a file to see if certain information exists. If it doesn’t then write it to a file.

This program asks the user to enter their names, email address and the number of years they have been teaching. It then looks in the file to see if the email address already exists. If it doesn’t it will write the information entered to a file, if it does it will say that person already exists.

The CSV file looks like this:

#ask the user to enter four pieces of information
firstname = input("Enter your first name: ")
surname = input("Enter your surname: ")
email = input("Enter your email: ")
yearsteaching = input("Enter the number of years teaching: ")
file = open("staff.csv", "r") #opens the file in read mode
found = False #sets whether the user is found to False
for line in file: #reads each line in the file
    staff = line.split(",") #splits the line into the list called staff
    if staff[2] == email: #checks if the email entered is in the list
        found = True #if it is changes found to True
file.close() #closes the file
if found == True: #after the loop checks if the user is found
    print("Staff member already exists in the file") #displays on screen
else:
    #if the email was not in the file
    writefile=open("staff.csv", "a") #open the file in append mode
    writefile.write(firstname + "," + surname + "," + email + "," + yearsteaching) #write the new information to the file
    writefile.close() #close the file
    print("Staff member added to file")

When run in IDLE:

Example Program 3

Reading data from one file and writing to a separate file

This program looks through a file that contains a list of students and the scores that they have got in four tests. When run it should calculate the average score for each student. If it is over 50 it should write their name and their average score to a new file, if not it should do nothing. The program should also count how many people have averaged above 50.

The CSV file looks like this:

total = 0
average = 0
students_over_50 = 0 #variable to store how many students have averaged over 50
print("Students who have averaged over 50")
file = open("testscores.csv","r") #opens the file in read mode
for line in file: #reads each line in the file
    scores = line.split(",") #splits the line into the list called scores
    total = int(scores[3]) + int(scores[4]) + int(scores[5]) + int(scores[6]) #adds up the four test scores
    average = total / 4 #calculates the average of the four test scores
    if average > 50: #checks if the average is more than 50
        print(scores[0] + "\t" + scores[1] + "\t" + scores[2] + "\t" + str(average)) #prints the name, class and average score
        students_over_50 = students_over_50 + 1 #adds 1 to the number of students averaging over 50
        writefile = open("average_over_50.csv","a") #opens the file average_over_50.csv in append mode
        writefile.write(scores[0] + "," + scores[1] + "," + scores[2] + "," + str(average)+"\n") #writes the same information that has been printed to screen to file
        writefile.close() #closes the file
if students_over_50 == 0: #after the loop checks if the students_over_50 variable is 0
    print("There were no students that averaged over 50") #if it is then say no students averaged over 50
else:
    print("The number of students averaging over 50 was " + students_over_50) #if not says how many averaged over 50.

The program when run: