繁体   English   中英

如何grep文件名并将其存储在python输出中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM