CSV, lists, and functions

Roy Smith roy at panix.com
Wed Mar 20 00:19:07 CET 2013


In article <1d7fcebe-8677-42ec-a53d-284214296d37 at googlegroups.com>,
 "C.T." <swilks06 at gmail.com> wrote:

> Currently doing a project for class an I'm stuck. I have a csv file that I'm 
> suppose to extract some information from. I've created a function that 
> ignores the first six lines of the csv file and creates a list of values in a 
> particular column. Here is the code:
> 
> 
> def get_values(file, index):
> 
>     '''(file object, int) -> list
>     Return a list of states and corresponding values at a prticular index in 
>     file.'''
>     
>     values_list = [] 
>     file.readlines(900)#skipping first 6 lines of file

Your intent is to skip the first 6 lines, but your code says "skip the 
first 900 characters, plus enough to get to the end of the next line".  
You're assuming 900 characters gets you to line 6.  That's really 
fragile.

If you really want to skip the first 6 lines, try something like:

for i in range(6):
   file.readline()

The next problem I see is:

    for line in file:
        line_list = line.split(',')

You don't want to do that.  Use the csv module 
(http://docs.python.org/2/library/csv.html) to parse the file.  It 
handles quotes, embedded commas, and all sorts of annoying edge cases 
you've probably never thought of.



More information about the Python-list mailing list