[英]How to grep the names of files and store it in output with python
I have a directory that has multiple files and I want to grep only test.uwsgi.log
files and remove the .uwsgi.log part. 我有一个包含多个文件的目录,我只想grep
test.uwsgi.log
文件并删除.uwsgi.log部分。 After greping the names I store it in a output file. 命名后,我将其存储在输出文件中。
Here is what I got: 这是我得到的:
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])
and the output is : 输出为:
test1
test2
test3
Can someone educate me on how to achieve this without the subprocess module and use python only? 有人可以教我如何在没有子流程模块的情况下实现这一目标,而仅使用python吗?
Using Python alone: 单独使用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 is as expected: output.txt符合预期:
test1
test2
test3
Notice I added \\n
to each element in the list comprehension . 注意,我将
\\n
添加到列表推导中的每个元素。 as writelines
does not do it automatically. 因为
writelines
不会自动执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.