簡體   English   中英

cat 和 grep 來自 python 中的多個文件並將 output 寫入文件?

[英]cat and grep from multiple files in python and write output to a file?

我想要一個 python 等效於 shell 命令cat logs/archived/app.2020-12-11* | grep "Sending" > sms_otp_logs_ack.log cat logs/archived/app.2020-12-11* | grep "Sending" > sms_otp_logs_ack.log

我嘗試過使用 sh 模塊。

sh.grep(sh.cat(2020-12-18/100.6.13.16/app.*), string_to_grep)

由於 * 通配符,這會引發沒有此類文件的錯誤。 我怎樣才能 pypass 這個並將 output 保存到另一個文件?

您可以使用glob模塊,該模塊根據 Unix shell 使用的規則查找與指定模式匹配的所有路徑名,然后以讀取模式打開找到的文件以搜索所需的字符串( "Sending" ),以便包含該字符串的行將被附加到另一個文件中。

import glob, os

for f in glob.glob(os.path.join(path, "app.2020-12-11*")):
    with open(f, 'r') as f_in, open('sms_otp_logs_ack.log', 'a') as f_out:
        for line in f_in:
            if "Sending" in line:
                f_out.write(line)

暫無
暫無

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

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