Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use os.listdir to show directories only [duplicate]

How can I bring python to only output directories via os.listdir, while specifying which directory to list via raw_input?

What I have:

file_to_search = raw_input("which file to search?\n>")

dirlist=[]

for filename in os.listdir(file_to_search):
    if os.path.isdir(filename) == True:
        dirlist.append(filename)

print dirlist

Now this actually works if I input (via raw_input) the current working directory. However, if I put in anything else, the list returns empty. I tried to divide and conquer this problem but individually every code piece works as intended.

like image 533
Felix Avatar asked Aug 24 '17 21:08

Felix


1 Answers

that's expected, since os.listdir only returns the names of the files/dirs, so objects are not found, unless you're running it in the current directory.

You have to join to scanned directory to compute the full path for it to work:

for filename in os.listdir(file_to_search):
    if os.path.isdir(os.path.join(file_to_search,filename)):
        dirlist.append(filename)

note the list comprehension version:

dirlist = [filename for filename in os.listdir(file_to_search) if os.path.isdir(os.path.join(file_to_search,filename))]
like image 173
Jean-François Fabre Avatar answered Sep 20 '22 04:09

Jean-François Fabre