簡體   English   中英

使用 python 從文件夾中讀取多個日志文件

[英]Reading multiple log files from a folder using python

過去,我使用 python 讀取了一個日志文件,代碼如下,一直運行良好:

with open(r"24T23.log") as f, open('logfile.csv', 'w') as f2:
    writer = csv.writer(f2)
    writer.writerow(['Index','Date', 'Time', 'Logic', '(Logic)','Type', 'Code','Connector', 'Message', 'Extra 1', 'Extra 2'])

    i = 0
    for line in f:
        writer.writerow([i] + line.rstrip().split('\t'))
        i += 1

對於我正在處理的特定用例,我需要讀取一個文件夾中包含的多個文件。 有人可以建議如何修改上面的代碼(我嘗試使用 blob 但未能成功)? 提前致謝。

這個怎么樣?

import csv
import os

# From root of cwd
DIRECTORY = 'test'

# This gets the path of every file in DIRECTORY if it is a log file
# os.path.join(os.getcwd(),x) to include cwd in directory name
logs = [os.path.join(os.getcwd(), x) for x in os.listdir(
    DIRECTORY) if os.path.splitext(x)[1] == '.log']

for log in logs:
    # Note the 'a' append write, to append the rows to the files
    with open(log) as f, open('logfile.csv', 'a') as f2:
        writer = csv.writer(f2)
        writer.writerow(['Index', 'Date', 'Time', 'Logic', '(Logic)',
                        'Type', 'Code', 'Connector', 'Message', 'Extra 1', 'Extra 2'])

        i = 0
        for line in f:
            writer.writerow([i] + line.rstrip().split('\t'))
            i += 1

關於os.listdir()的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM