os.listdir doesn't work outside current directory

Viewed 376

I have the following code:

import os

myPath = "/Users/myusername/"
listOfDirs = []

for d in os.listdir(myPath):
    if os.path.isdir(d):
        listOfDirs.append(d)
        
print(listOfDirs)

As long as the python file that contains the above is at the same location as myPath in above example, the listOfDirs will return a list of all the directories in myPath. If I change the myPath to a path different than where the script itself is (for example, /Users/myusername/subdirectory/, a directory I have permission for), I will end up with an empty list.

How do I get the os.listdir to work at any given path, even if it's different than the location of the script?

Thanks for any help.

1 Answers

The list returned by os.listdir(myPath) is relative to myPath so you have to concatenate myPath and d:

for d in os.listdir(myPath):
    if os.path.isdir(os.path.join(myPath, d)):
        listOfDirs.append(d)

You can use pathlib module as replacement:

import pathlib

listOfDirs = list(pathlib.Path(myPath).iterdir())

See the correspondence between pathlib and os

Related