When working with data sets, a common task I need to do is slurp a csv file into a nested data structure that contains a sequence of lists correlating to the rows and values in the csv file.
For example...
File contents (foo.csv):
10,20,30,4019,29,39,5516,21,31,59
Result:
[['10', '20', '30', '40'], ['19', '29', '39', '55'], ['16', '21', '31', '59']]
To accomplish this. you could parse it inside a big honkin' list comprehension and build our structure in one step:
csv_file = 'foo.csv'value_lists = [line.split(',') for line in [line.strip() for line in open(csv_file, 'r').readlines()]]
You could also use the csv module from Python's standard library:
import csvcsv_file = 'foo.csv'value_lists = list(csv.reader(open(csv_file, 'r')))
The csv module has some useful tools for reading/writing csv files. Check it out.
Copyright © 2006-2008 Corey Goldberg
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.