简体   繁体   English

为什么两个“ for循环”都不起作用?

[英]Why aren't both “for loops” working?

import csv

def csv_reader(file_obj):      
    reader = csv.reader(file_obj)
    # for row in reader:
        # print(" ".join(row))

    reader_2 = csv.DictReader(file_obj, delimiter=",")
    for row_2 in reader_2:
        print(row_2)

csv_path = "data.csv"
with open(csv_path, "r") as f_obj:
    csv_reader(f_obj)

I can't figure out why the second "for loop" only prints any text if the first "for loop" is commented out. 我不知道为什么如果第一个“ for循环”被注释掉,第二个“ for循环”仅输出任何文本。

The CSV reader has already consumed your file. CSV阅读器已经消耗了您的文件。 Calling file_obj.seek(0) before using it again should do the trick. 再次使用file_obj.seek(0)之前应该可以解决这个问题。

Alternatively, opening (and then closing) the file for each operation will also work. 或者,也可以为每个操作打开(然后关闭)文件。

It's because you are passing the same file handler to both csv reader objects. 这是因为您要将相同的文件处理程序传递给两个csv阅读器对象。 Once you iterate over it once, you have to manually do file_obj.seek(0) for it to work as intended, or else it simply acts like an empty file. 一旦对其进行迭代,就必须手动执行file_obj.seek(0)使其按预期工作,否则它就像一个空文件。

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

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