47. Writing a list into a file

  • A really important thing you will need to be able to do is read and write text files with variable numbers of lines
  • Because we don’t know how many lines there will be, we tend to read text files into a list, make any changes, and then write the whole list back over the file
#List held in program
address_list = [
['Ken McCall', '65 Lincoln Blvd', 'Washington', '07989 345664'],
['Joe Smith', '21 Jefferson Ave', 'Washington', '07664 354748'],
['Ally Major', '99 Kennedy St', 'Washington', '08775 467362'],
['Jay Jones', '57 3rd St', 'Delaware', '08556 474562']
]

#Open the file
file = open("addresses.csv","w")

#Loop through each line of the list
for line in address_list:

    #Build line to write to the file, each part separated by a comma,
    #and a line break \n at the end
    file.write(line[0] + "," + line[1] + "," + line[2] + "," + line[3] + "\n")

#Close the file
file.close()

Tasks

  • Type in the code and make sure it works
  • Add two more people into the list (there are several ways to do this)
  • Modify the code to allow you to choose a filename
  • Save and label your code

Extension Task

Python can be buggy if it tries to write to a file that is open in another program such as notepad. Try it and see what happens