12

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.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Felix
  • 123
  • 1
  • 1
  • 5
  • Could you share what you entered in the `raw_input` field and what OS you use? – MSeifert Aug 24 '17 at 21:12
  • Just for the record since Jean-Francois solution worked: examples of what I entered: C:/, D:/X/Y, C:\, D:\X\Y, D:\\X\\Y OS: Windows – Felix Aug 24 '17 at 21:30

1 Answers1

19

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))]
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 2
    Better use walk here see https://stackoverflow.com/a/63715910/281545 `dirlist = [d for d in next(os.walk(file_ro_search))[1]]` – Mr_and_Mrs_D Oct 31 '21 at 10:19