简体   繁体   English

如何在python中分别读取csv文件的两个字段?

[英]How can read two field of a csv file separately in python?

I want to read two column of a csv file separately, but when I wrote code like below python just show first column and nothing for second, but in the csv file the second column also has lots of rows. 我想分别读取csv文件的两列,但是当我在python下面编写类似代码的代码时,只显示第一列而不显示第二列,但是在csv文件中,第二列也有很多行。

import csv
import pprint

f = open("arachnid.csv", 'r')
read = csv.DictReader(f)
for i in range(3):
    read.next()

for i in read:
    pprint.pprint(i["binomialAuthority_label"])

for i in read:
    pprint.pprint(i["rdf-schema#label"])

The reason for this is that when you use DictReader the way you are using it it will create what is called an iterator/generator. 这样做的原因是,当您按自己的方式使用DictReader时,它将创建称为迭代器/生成器的东西。 So, when you have iterated over it once, you cannot iterate over it again the way you are doing it. 因此,当您对它进行一次迭代时, 就无法再按其执行方式对其进行迭代。

If you want to keep your logic as is, you can actually call seek(0) on your file reader object to reset its position as such: 如果要保持逻辑不变,则实际上可以在文件读取器对象上调用seek(0)来重置其位置,如下所示:

f.seek(0)

The next time you iterate over your dictreader object, it will give you what you are looking for. 下次您遍历dictreader对象时,它将为您提供所需的内容。 So the part of your code of interest would be this: 因此,您感兴趣的代码部分将是这样的:

for i in read:
    pprint.pprint(i["binomialAuthority_label"])

# This is where you set your seek(0) before the second loop
f.seek(0)

for i in read:
    pprint.pprint(i['rdf-schema#label'])

Your DictReader instance gets exhausted after your first for i in read: loop, so when you try to do your second loop, there is nothing to iterate over. 您的DictReader实例for i in read:循环中的第一个for i in read:之后就筋疲力尽了,因此当您尝试进行第二个循环时,没有什么可以重复的。

What you want to do, once you've iterated over the CSV the first time, you can seek your file back to the start, and create a new instance of the DictReader and start again. 要做的是,第一次遍历CSV之后,您可以将文件找回来,并创建DictReader的新实例,然后重新开始。 You'll want to create a new DictReader instance otherwise you'll need to manually skip the header line. 您将要创建一个新的DictReader实例,否则需要手动跳过标题行。

f = open(filename)
read = csv.DictReader(f)
for i in read:
    print i

f.seek(0)
read = csv.DictReader(f)
for i in read:
    print i

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

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