Reputation: 12628
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?
Upvotes: 2
Views: 1255
Reputation: 7617
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")
Upvotes: 1
Reputation: 40783
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.
Upvotes: 1
Reputation: 8004
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
Upvotes: 1
Reputation: 1
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
Upvotes: 0
Reputation: 146
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) ??
Upvotes: -1