46. Reading a file into a list

  • 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
#Define blank list
file_contents = []

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

#Loop through each line
for line in file:

    #Strip the \n fron the line
    line = line.strip("\n")

    #Split the line into parts
    name,address,city,phone = line.split(",")

    #Add items to file_contents list
    file_contents.append([name,address,city,phone])

#Close the file
file.close()

#Messy print
print(file_contents)

Tasks

  • Type in the code and make sure it works
  • Modify the code to allow you to choose a filename
  • Modify the code to print the list in a neater fashion
  • Save and label your code

Extension Task

You can make this code more efficient by combining the splitting and appending into one line (shown below). Implement this improvement

file_contents.append(line.split(","))