# The first 4 functions demonstrate how to read in a csv formatted # file using standard reading of a file. It requires splitting # each line of the list of lines so that in the end, the implied # table of information from the file is loaded into a list of lists # data structure. Each high level list entry represents a row from # the csv file, and furthermore, each row is represented by a list # of items. # A file like this: # head1, head2, head3 # cat, dog, fish # one, two, three # # becomes: # [["head1","head2","head3"],["cat","dog", "fish"], ["one","two","three"]] def readData(filename): f = open(filename, "r") data = f.readlines() f.close() return data def removeBlankLines(data): # removes blank lines and \n goodLines = [] for line in data: line = line.rstrip() if len(line) != 0: goodLines.append(line) return goodLines def splitLines(data): newLines = [] for line in data: myList = line.split(", ") # not a great way to avoid spaces newLines.append(myList) return newLines def driver(): rawDataList = readData("asotv.csv") cleanDataList = removeBlankLines(rawDataList) csvDataList = splitLines(cleanDataList) print(csvDataList) ############## # Now a somewhat equivalent solution using the csv module of Python 3. def readCSVExample(filename="asotv.csv"): import csv # You'll need to create lines as an empty list if you are # going to build it yourself # lines = [] f = open(filename) # below specifying delimiter & quotechar is the same as # the default dialect="excel" csvReader = csv.reader(f, delimiter=",", quotechar='"') # code the adding of rows to the lines list yourself as below #for row in csvReader: # lines.append(row) # or simply use the list function to form a list # from the iterable reader object lines = list(csvReader) f.close() return lines