簡體   English   中英

使用Python中的`for`循環解析多個文件(相同格式)

[英]Parsing multiple files (same format) use `for` loop in Python

我正在開發一個Python腳本,在其中我要掃描整個子目錄以查找.log文件。

要獲取.log文件列表,我可以獲取文件名。 這是代碼。

for root, dirs, files in os.walk("Directory to be analyse"):
    for file in files:
        if file.endswith('.log'):

現在,如何遍歷for循環中的所有文件並獲取其內容?

嘗試;

import os
for root, dirs, files in os.walk(r'path to open'):
    for file in files:
        if file.endswith('.log'):
            with open(os.path.join(root, file)) as stream:
                for lin in stream:
                    # lin containg the content of each line in the file

您可以使用os.path.join獲取打開文件的完整路徑

在if塊中,可以在with open塊中打開文件並讀取每一行。

if file.endswith('.log'):
    with open(file,'r') as f:
        for line in f:
            pass  #Do something with each line in the opened file
    print '{} has been closed'.format(file)

希望這可以幫助!

如果您可以使用bash進行此操作,那么一個襯板就可以了

DIR='Directory to be analyse'    
sudo find $DIR -iname \*.log -exec cat {} \;

暫無
暫無

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

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