• Uncategorized

About python : oslistdir-and-ospathisdir-confusion-isdir-is-acting-random

Question Detail

I have this simple process below for listing the contents of a folder:

def some_process(self):

    dir3 = os.listdir('/Users/somepath/programming/somepathanother/Data_samples')
    for d in dir3:
        if os.path.isdir(d):
            print "DIR: " + d
        elif os.path.isfile(d):
            print "FILE: " + d

    print "PATH THREE:"
    print str(dir3)


The actual contents of the Data_samples folder is:

The output of the process does not work as expected. For a file it just prints:

FILE .DS_Store
and nothing else (should print out file.zip and anotherfile.zip)

I also realize that if I copy the resourcetest.py file and it’s corresponding ini file into this folder and run it then it does see it

FILE: .DS_Store
FILE: resourcetest.ini
FILE: resourcetest.py

The full output of print str(dir3)

['.DS_Store', 'dir1', 'dir2', 'dir3', 'dir4', 'resourcetest.ini','resourcetest.py', 'test.file', 'test.zip', 'dir5']

Then should also print out dir1 dir2 dir3 dir4 as DIR: ” , yet none of this happens and I have no idea why, though in an odd twist if I execute this code from the folder that is listed, it does show everything correctly.

Is this an anomaly of running python 2.7 from the mac os x terminal, or am I missing something else here. Is my thinking on the usage of listdir and isdir wrong?

Question Answer

listdir gives only the names, not the full path. You will need to create the full path:

for d in dir3:
    path = os.path.join('/Users/somepath/programming/somepathanother/Data_samples', d)
    if os.path.isdir(path):

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.