【问题标题】:Why isn't the tqdm progress bar showing up on my csv reader loop?为什么 tqdm 进度条没有出现在我的 csv 阅读器循环中?
【发布时间】:2020-05-14 14:39:42
【问题描述】:

我尝试了几种不同的方法,但到目前为止,我的代码都没有。我最终破坏了我的脚本,所以它只显示一个空的进度并且脚本结束而不是实际做它应该做的事情。如何在脚本的这一部分正确添加 tqdm 进度条?

def add_column_in_csv(input_file, output_file, transform_row):
    # open input file and create output file
    with open(input_file, 'r') as read_obj, \
        open(output_file, 'wb') as write_obj:
        # create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        lines = len(list(read_obj))
        print lines
        # read each row of the input csv file as list
        for row in tqdm(csv_reader, total=len(list(read_obj))):
            # append the headers and values from checks in add_to_row
            transform_row(row, csv_reader.line_num)
            # add the updated row to the output file
            csv_writer.writerow(row)


# let them know it is doing something
print('Analyzing input file . . .')
# actually add the data to the new csv here
add_column_in_csv(input_file, output_file, add_to_row)
# it is done
print('Done analyzing file. Output created: ' + str(output_file))

这样做似乎不会在 for 循环中执行我的代码。它在 0% 处显示一个没有进度的进度条并显示 0/17(这是我的 csv 中的行数),然后打印我的最后一行“完成分析文件。输出已创建:',但输出 csv 为空白。但是,如果我完全删除 total=len(list(read_obj)) 脚本确实会运行,并且至少会显示发生的迭代次数和花费的时间,但没有进度条。

【问题讨论】:

    标签: python tqdm


    【解决方案1】:
    for row in tqdm(csv_reader, total=len(read_obj.read().split('\n'))):
        # append the headers and values from checks in add_to_row
                transform_row(row, csv_reader.line_num)
                # add the updated row to the output file
                csv_writer.writerow(row)
    

    【讨论】:

    • 这不起作用,因为文件的对象类型没有 len()。但是,我在执行 total=len(list(read_obj)) 时尝试了类似的操作,但在执行此操作时,我的大部分脚本实际上并没有运行,因为它只打印出 0% 的进度条并完成。由于某种我不太明白的原因,它似乎基本上忽略了 for 循环中的行。
    • 我认为这是因为 list read_obj 没有将文件拆分为行,所以尝试更新的方法,当文件被新行拆分时,您使用列表的长度
    • 我很确定该列表可以正常工作,因为如果我执行 lines = len(list(read_obj)) 并打印 lines 它会输出文件中的行数。我的主要问题是,每当我在上面或 for 循环中添加一些东西时,脚本都没有完全运行。由于某种原因,实际的循环没有运行。
    • 你的导入声明是from tqdm import tqdm吗?
    • 是的。我在最初的帖子中编辑了我的代码,其中包含更多上下文,因为可能值得注意的是 csv 部分是我正在调用的它自己的函数
    猜你喜欢
    • 1970-01-01
    • 2018-01-30
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 2021-08-20
    • 2023-03-22
    • 2018-10-12
    相关资源
    最近更新 更多