tags:

views:

49

answers:

1

With header information in csv file, city can be grabbed as:

city = row['city']

Now how to assume that csv file does not have headers, there is only 1 column, and column is city.

+2  A: 

You can still use your line, if you declare the headers yourself, since you know it:

with open('data.csv') as f:
    cf = csv.DictReader(f, fieldnames=['city'])
    for row in cf:
        print row['city']

For more information check csv.DictReader info in the docs.

Another option is to just use positional indexing, since you know there's only one column:

with open('data.csv') as f:
    cf = csv.reader(f)
    for row in cf:
        print row[0]
nosklo
this works for if there were headers, but what if the csv file does not have headers, we have to assume, if it is 1 column, it is city.
bobsr
@bobsr: no, you're wrong. Both snippets of code I provided work when the file has **no headers** at all.
nosklo
yes, they do, thanks
bobsr