44. Reading Delimited Files

  • Sometimes, you need to read in files from other programs containing information such as student records or address details.
  • We use files known as comma separated values files
  • They are simply text files with a different extension (.csv)
  • Each line will have multiple items on it, each usually separated by a comma. It might look like the example below
  • When working with files, make sure they are NOT open in notepad whilst Python is running
  • There should be NO spaces between line items
#Open file for reading
file = open("addresses.csv","r")

#Read into list and split at commas
for line in file:

    #Strip the \n from the end of the line
    line = line.strip("\n")

    #Split the line into separate variables
    name,address,state,phone = line.split(",")

    #Print the variables
    print(name,address,state,phone)

#Close file, contents now in list
file.close()

Tasks

  • Create a suitable .csv file with details of 5 people in it
  • Type in the code above and make sure it works
  • Save and label your code

Extension Task

This code is very basic and will break very easily if the file does not exist. A function called exists() can be used to check for a file before trying to open it. Do some research and try to implement a feature that detects if the file exists