简体   繁体   English

Scope 变量在 Python 中使用 csv 读卡器

[英]Scope of variables using csv reader in Python

When I run this function on the file with 10 lines, it prints out the lines, but returns the length of 0. If I reverse the order, it prints out the length, but not the file content.当我在有 10 行的文件上运行此 function 时,它会打印出这些行,但返回的长度为 0。如果我颠倒顺序,它会打印出长度,但不会打印出文件内容。 I suppose this is a scope related issue, but not sure how to fix it我想这是与 scope 相关的问题,但不知道如何解决

def read_samples(name):
    with open ( '../data/samples/' + name + '.csv', encoding='utf-8', newline='') as file:
        data = csv.reader(file)
        for row in data:
            print (row)
        lines = len ( list ( data ) )
        print(lines)

You are getting 0 because you have already looped over data.So now it is 0 .It is an iterator which is consumed.你得到 0 因为你已经循环了数据。所以现在它是0 。它是一个被消耗的迭代器。

def read_samples(name):
    with open ( '../data/samples/' + name + '.csv', encoding='utf-8', newline='') as file:
        data = csv.reader(file)
        x=0
        for row in data:
            x+=1
            print (row)
        lines = x
        print(lines)

The csv.reader() function returns an iterator (which are "consumed" when you use them) so you can only use data once. csv.reader() function 返回一个迭代器(当你使用它们时它是“消耗的”),所以你只能使用一次data You can coerce convert it to a list before you do any operations on it to do what you want, eg data = list(data) .您可以在对其进行任何操作以执行您想要的操作之前强制将其转换为列表,例如data = list(data)

The file reader remembers its place in the file like a bookmark文件阅读器像书签一样记住它在文件中的位置

Printing each line and getting the length both move the bookmark all the way to the end of the file打印每一行并获取长度都将书签一直移动到文件末尾

Add data.seek(0) between the loop and getting the length.在循环之间添加data.seek(0)并获取长度。 This moves the bookmark back to the start of the file这会将书签移回文件的开头

Try尝试

def read_samples(name):
    with open ( '../data/samples/' + name + '.csv', encoding='utf-8', newline='') as file:
        my_list = []
        data = csv.reader(file)
        for row in data:
            print (row)
            my_list.append(row)
        lines = len (my_list)
        print(lines)

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

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