2

I am running a terminal command to list a directory, I would like to loop through each line returned and search for a particular filename, I have this so far...

import subprocess

for line in subprocess.check_output(['ls', '-l']):
    if "(myfile.txt)" in line: 
        print("File Found")

But this is just outputing the list and doesn't seem to be searching for the file, anyone have an example they can point me at?

5 Answers 5

1

Calling ls from within subprocess would return a Bytes Object.
So, first, You might want to convert the returned value to a String.
And then split the String with New-Line ("\n") as delimiter.
Afterwards, you can iterate and search for your Needle in the List-Values.

import subprocess
# CALLING "subprocess.check_output(['ls', '-l']" RETURNS BYTES OBJECT...
# SO WE DECODE THE BYTES INTO STRING, FIRST
# AND THEN SPLIT AT THE NEW-LINE BOUNDARY TO CONVERT IT TO A LIST
for line in bytes.decode(subprocess.check_output(['ls', '-l'])).split(sep="\n"):
    # NOW WE CAN CHECK IF THE DESIRED FILE IS IN THE LINE
    if "(myfile.txt)" in line:
        print("File Found")
Sign up to request clarification or add additional context in comments.

2 Comments

Your explanation is kind of misleading. I think it is not the ls function that returns a Bytes object but this is what check_output returns. Also, the Bytes object is iterable. You can try to iterate over it.
@Tai Thanks for Pointing that out :-)
1

You can try to pass in the encoding utf-8 and split it by \n.

for line in subprocess.check_output(['ls', '-l'], encoding="utf-8").split("\n"):
    # print(line)
    if "myfile.txt" in line: 
         print("File Found")

As originally, check_output was returning bytes, thus we pass in encoding here. Also, since you want to search it line by line, we split it with \n. (Tested on Python 3.)

subprocess.check_output: ... By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level.

This behaviour may be overridden by setting universal_newlines to True as described above in Frequently Used Arguments. -- cited from https://docs.python.org/3/library/subprocess.html#subprocess.check_output

Comments

1

Why not use something that is more reliable such as os.listdir or glob:

import glob

if glob.glob('myfile.txt'):
    print('File found')
else:
    print('File not found')

The glob.glob function returns a list of files that match the wildcard. In this case, you will have ['myfile.txt'] if the file exists, or [] if not.

1 Comment

That would be perfectly ideal if he was interested in doing it directly. Perhaps he's just experimenting with the subprocess module.... However, if not for any valid reason, your solution would be most appropriate and straightforward.
0
import os
 def find(name):
    for root, dirs, files in os.walk('C:\\');
        if name in files:
            print(root,name)
            print("FINISH")
            input()

try:
    s=input("name:  ")
    find(s)
except:
    None

1 Comment

Please also add some info in ordinary text on how this answers OP's question.
-1

to output the contents of a directory, i would recommend the os module.

import os

content = os.listdir(os.getcwd())

then you have a searchable list.

But are you sure, your file ist named (myfile.txt) ??

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.