PyRsquared
PyRsquared

Reputation: 7338

How to specify directory using glob in python?

Say I have a list of directories dirs.

dirs = ['C:\\path\\to\\dir1','C:\\path\\to\\dir2','C:\\path\\to\\dir3']

And in each of these directories, there are several excel files I want to get a list of. If I just use glob.glob("*.xls*") this only gives me a list of excel files in my current working directory, but I want to specifically get a list of the excel files in "C:\path\to\dir1", "C:\path\to\dir2" etc.

I have tried

import glob
for direc in dirs:
    print(glob.glob(direc + "*.xls*")
>>>[]

but this just produces empty lists.

What am I doing wrong here? How can I get a list of the excel files in each of the directories in dirs?

Upvotes: 5

Views: 5535

Answers (1)

goks
goks

Reputation: 1206

You can use os.walk()

import os 
   for root,dirs,files in os.walk('C:\\path\\to\\'):
        for names in files:
            if names.endswith('.xls'):
               print(os.path.join(root, names))

Upvotes: 4

Related Questions