【问题标题】:I'm trying to read a CSV file only if it i has between 200 and 400 records [duplicate]只有当我有 200 到 400 条记录时,我才尝试读取 CSV 文件 [重复]
【发布时间】:2020-07-29 08:07:27
【问题描述】:

只有在 200 到 400 条记录之间,我才尝试读取 CSV 文件。否则我希望它忽略。由于某些奇怪的原因,我的代码从未到达 print(row)

with open(file) as csv_file:
    row_count = sum(1 for line in csv_file)
    if (row_count>200 and row_count<400):
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            print(row)

【问题讨论】:

  • csv_file 是一个迭代器;在你用sum 循环它之后,它已经用尽了。

标签: python csv csvreader


【解决方案1】:

您忘记从文件中读取数据。要获取您需要的数据csv_file.read() 即便如此,文件的处理也有很多麻烦。

我建议使用pandas 模块,因为它很简单。

import pandas as pd

data =  pd.read_csv(r'filepath')
if 200<len(data)<400:
    print('True',len(data))

【讨论】:

    【解决方案2】:

    我仍在尝试找出原因,但您需要在执行完行数后再次读取文件。

    with open(file) as csv_file:
        row_count = sum(1 for line in csv_file)
    
    if (row_count > 200 and row_count < 400):
        with open(file) as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            for row in csv_reader:
                print(row)
    

    【讨论】:

    • 谢谢snakecharmerb,这解释了它 - csv_file 是一个迭代器;在你用 sum 遍历它之后,它已经用尽了
    • 这里也有一个很好的答案->stackoverflow.com/a/27504076/4285029
    猜你喜欢
    • 2013-02-02
    • 1970-01-01
    • 2021-02-28
    • 2019-02-20
    • 2019-04-26
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多