[英]How to grep the names of files and store it in output with python
我有一個包含多個文件的目錄,我只想grep test.uwsgi.log
文件並刪除.uwsgi.log部分。 命名后,我將其存儲在輸出文件中。
這是我得到的:
import subprocess
testlist = “cd /root/test/ && ls | grep ‘uwsgi.log' |sed 's/\.uwsgi.log\>//g' > /root/test/testlist.txt"
output = subprocess.check_output(['bash','-c', testlist])
輸出為:
test1
test2
test3
有人可以教我如何在沒有子流程模塊的情況下實現這一目標,而僅使用python嗎?
單獨使用Python:
import os
for _, dirs, files in os.walk('/root/test/'):
with open('output.txt', 'w') as out_file:
out_file.writelines("{}\n".format(f) for f in files if f.endswith('uwsgi.log'))
output.txt符合預期:
test1
test2
test3
注意,我將\\n
添加到列表推導中的每個元素。 因為writelines
不會自動執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.