简体   繁体   中英

How to enumerate a .csv file in python?

I have a byCCD.csv file which contains like

1,2014-08-18,India,3
1,2014-08-18,United States,2
1,2014-08-24,India,2
1,2014-08-24,United States,0

I have a Python function to parse the .csv file

 def parseCCDfile():
    with open('byCCD.csv', 'rb') as f:
      reader = csv.reader(f)
      for r, row in enumerate(reader):
         for id, d, ccd, cnt in enumerate(row):
            # logic for parsing the file

I am getting error as : ValueError: need more than 2 values to unpack Please help to correct this

You are already looping over each row, you don't need to loop over the columns either.

Remove the line:

for id, d, ccd, cnt in enumerate(row):

because looping over the row produces one value at a time, plus the enumerate() index.

You can instead assign those values in the other loop:

for r, (id, d, ccd, cnt) in enumerate(reader):

or use a tuple assignment:

for r, row in enumerate(reader):
    id, d, ccd, cnt = row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM