【问题标题】:Python Progress Bar in nested loop嵌套循环中的 Python 进度条
【发布时间】:2018-12-01 19:53:36
【问题描述】:

我正在将一些 linux 日志数据转换为 CSV 用于数据分析。有些说明需要一些时间,所以我想我会为每个正在翻译的文件添加一个进度条。但是,当使用progresspar2 或tqdm 放入进度条时,我的pandas 数据框和null。根本没有数据。当我删除进度条时,一切正常。

这是我的 CSV 翻译函数:

import pandas as pd
from dateutil import parser
from tqdm import trange
import os
import glob
import csv
import socket


def logsToCSV():
print("[+] Translating log to CSV")
log_file = open(CSV_FILE_PATH, "w", newline='')
csv_w = csv.writer(log_file)

for filename in glob.glob(os.path.join(LOGS_FILE_PATH, '*.txt')):       # Find all files in path with .txt
    data_file = open(filename, "r")
    file_length = len(data_file.readlines())

    for i in trange(file_length, desc='loop', leave=False):             # Progress Bar Via TQDM
        for new_line in data_file:

            new_line = line.strip().split(" ")
            date = str("%s %s %s" % (new_line[0], new_line[1], new_line[2])).strip()
            date = parser.parse(date)
            ip =str(new_line[5]).partition("/")
            ip = str(ip[0]).strip()
            try:
                url = str(new_line[7]).strip()
            except:
                url = None
            csv_w.writerow([date,ip,url])

TQDM 正在破坏某些东西,或者我执行不正确。

编辑 1:

我想通了。我在 readlines() 期间用尽了读取的文件以获取长度。这有效:

def logsToCSV():
print("[+] Translating log to CSV")
log_file = open(CSV_FILE_PATH, "w", newline='')
csv_w = csv.writer(log_file)
path, dirs, files = next(os.walk(LOGS_FILE_PATH))
log_num = len(files)
print(log_num)

for filename in glob.glob(os.path.join(LOGS_FILE_PATH, '*.txt')):       # Find all files in path with .txt
    data_file = open(filename, "r")
    with open(filename, "r") as f:
        file_length = len(f.readlines())
    f.close()
    pbar = tqdm(total=file_length)
    for line in data_file:         
        new_line = line.strip().split(" ")
        date = str("%s %s %s" % (new_line[0], new_line[1], new_line[2])).strip()
        date = parser.parse(date)
        ip =str(new_line[5]).partition("/")
        ip = str(ip[0]).strip()
        try:
            url = str(new_line[7]).strip()
        except:
            url = None
        csv_w.writerow([date,ip,url])
        pbar.update(1)
    pbar.close()

【问题讨论】:

    标签: python python-3.x tqdm


    【解决方案1】:

    您可以为您的主循环应用 tqdm:

    从 tqdm 导入 tqdm for i in tqdam(条件):

    【讨论】:

      猜你喜欢
      • 2019-11-07
      • 2011-04-23
      • 2020-07-10
      • 2021-02-19
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      相关资源
      最近更新 更多