开发者

Reading each column from csv file

I want to read each column of a csv file and do some modification before storing them into table.

I have a csv files as :

"1";"testOne";"ValueOne"
"2";"testTwo";"ValueTwo"
"3";"testThree";"ValueThree"

Here I want to read the fi开发者_运维百科rst value "1" and then store it somewhere in a varaible and do something with this value, and similary with the others. However currently I can read the whole file, but could not find the way to access individual columns in a row.

Thank you.


Python has a built-in csv module.

import csv
with open('some.csv', 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    for row in reader:
        print row[0]


The answer up top is flexible and pythonic, but if you wanted something a bit more compact and slick for retrieving entire columns at a time from delimited data (that fits comfortably into memory), you could also try this:

c_reader = csv.reader(open('test.csv', 'r'), delimiter=';')

# say you want the second column, only...
col_2 = list(zip(*c_reader))[1] # keeping in mind that python is 0-indexed

# or if you want to come back for more later on, you can just do...
columns = list(zip(*c_reader))

A bit more traditionally pythonic than the former but still functional feeling would be:

# just using a good old list comprehension
col_2 = [x[1] for x in c_reader]

# you could also get all the rows simply in this way
rows = [x for x in c_reader]
row_2 = rows[1]

Now go forth and be one with the iterables! ;-)


You could use the csv python module:

class csv.DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[, *args, **kwds]]]]])

Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional fieldnames parameter. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames. If the row read has more fields than the fieldnames sequence, the remaining data is added as a sequence keyed by the value of restkey. If the row read has fewer fields than the fieldnames sequence, the remaining keys take the value of the optional restval parameter. Any other optional or keyword arguments are passed to the underlying reader instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜