- When writing to files, you can either overwrite the information in the file (w), or add to it as you go along (a). This is set as shown below. Choose one or the other, not both
- There is a function called writeline() that you might assume is the opposite of readline(). Using this is slightly different and we will simulate the same effect by adding a line break \n each time we write a line to the file
#Open file for appending (add to)
file = open(“savedfile.txt”,“a”)
#Open file for writing (overwrite)
file = open(“savedfile.txt”,“w”)
#Write one line at a time, note the addition of a line break \n on the ends
file.write("Jemima\n")
file.write("Asif\n")
file.write("Susan\n")
#Close file
file.close()
Tasks
- Type in the code and make sure it works – append will add names to the text file every time you run the code. Write will save over the previous names in the file
- Modify the program to accept user input to add 5 names to the file. There are several ways to do this, the most efficient using a for loop that runs 5 times
- Save and label your code
Extension Task
A while loop can be used to keep asking for names, and writing them to the file until a specific letter or character is typed in, such as ‘X’. How could you implement this feature? Can you make it work?