user7898237
user7898237

Reputation:

How to check if folder has suboflders and then list the directories with listdir()?

I want to write a file searching code where I don't know if the directory I'm searching in has subdirectories and I want to check that so I don't get an error like this: [Error 267]The directory name is invalid: 'C:/Path/To/Directory'. I wrote a code like this where if it finds the file it breaks and stopps the program but if not it goes down a layer and so on.

filename = raw_input('> ')
path = 'C:/Path/Of/Directory/You/Want/To/Search/In'
fldr = os.listdir(path)

for f in fldr:
    p = path + '/' + f
    sfldr = os.listdir(p)
    if os.path.exists(p + '/' + filename):
        print 'Found file!!', p + '/' + filename
        break
    else:    
        for sf in sfldr:
            pp = p + '/' + sf
            ssfldr = os.listdir(pp)
            if os.path.exists(pp + '/' + filename):
                print 'Found file!!', pp + '/' + filename
                break
            else:
                for ssf in ssfldr:
                    ppp = pp + '/' + ssf
                    sssfldr = os.listdir(ppp)
                    if os.path.exists(ppp + '/' + filename):
                        print 'Found file!!', ppp + '/' + filename
                        break

The easy to notice error is that when the directory doesn't have 3 layers of subfolders the program just breaks and gives an error message.So if I could check if the folder has subfolders before entering it,that would be neat.

Upvotes: 0

Views: 4679

Answers (1)

Rahul
Rahul

Reputation: 2598

Use os.scandir(). Provides better speed over os.walk()

Link to docs here!

Alternatively use, glob

>>> from glob import glob
>>> paths = glob('*/')
>>> paths
['bin/', 'content/', 'include/', 'lib/', 'output/']
>>> 

Upvotes: 1

Related Questions