• Uncategorized

About python : How-to-grep-the-names-of-files-and-store-it-in-output-with-python

Question Detail

I have a directory that has multiple files and I want to grep only test.uwsgi.log files and remove the .uwsgi.log part. 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 :


Can someone educate me on how to achieve this without the subprocess module and use python only?

Question Answer

Using Python alone:

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:


Notice I added \n to each element in the list comprehension . as writelines does not do it automatically.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.