简体   繁体   English

逐行读取csv文件

[英]read csv file row by row

I am using Python v2.7 (please don't ask me to use Python v3). 我正在使用Python v2.7(请不要让我使用Python v3)。 I have a csv file, its content is like this: 我有一个csv文件,其内容如下:

name age gender height
John 30  male   180
Kate 23  female 166
...

I use csv module. 我使用csv模块。 I try to read the content row by row with the following code: 我尝试使用以下代码逐行读取内容:

import csv

with open("data.csv", 'r') as data_file:
     reader = csv.reader(data_file, delimiter='\t')
     # ERROR: ValueError: need more than 2 values to unpack
     for name, age, gender, height in enumerate(reader):
         print name + ',' + age + ',' + gender + ',' + height

But I got error when run it: 但是运行它时出现错误:

ValueError: need more than 2 values to unpack

How to get rid of this error? 如何摆脱这个错误?

The issue that enumerate returns a tuple - item number and item itself. 枚举的问题返回一个元组-项目编号和项目本身。 So it returns two elements, and you forces it to unpack 4 elements instead(check https://docs.python.org/2/library/functions.html#enumerate ). 因此,它返回两个元素,而您则强制它解压缩4个元素(请检查https://docs.python.org/2/library/functions.html#enumerate )。 Try to transform it to: 尝试将其转换为:

for index, (name, age, gender, height) in enumerate(reader)

But actually I think you don't need enumerate function here since you don't use element index. 但是实际上我认为您不需要在这里枚举函数,因为您不使用元素索引。 If it won't work you can simply access a row by indexes as described in example in the doc: https://docs.python.org/2/library/csv.html#csv.reader 如果不起作用,您可以按照文档中示例中的描述按索引访问一行: https : //docs.python.org/2/library/csv.html#csv.reader

You are using enumerate() in the wrong way. 您使用错误的方式使用了enumerate()。 Please see this for further information: https://docs.python.org/2.3/whatsnew/section-enumerate.html 请参阅此以获取更多信息: https : //docs.python.org/2.3/whatsnew/section-enumerate.html

Regarding your code, you can do the following: 关于您的代码,您可以执行以下操作:

import csv

with open("data.csv", 'r') as data_file:
   reader = csv.reader(data_file, delimiter='\t')       
   for row in reader:
     print ', '.join(row)
import csv

with open("data.csv", 'r') as data_file:
  data_file.readline() # Skip first line
  reader = csv.reader(data_file, delimiter=',')
  for name, age, gender, height in reader:
     print name + ',' + age + ',' + gender + ',' + height

yields 产量

John, 30 , male  , 180
Kate, 23 , female, 166

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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