5

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?

5
  • 3
    try with print(glob.glob(direc + "/*.xls*") Commented May 9, 2018 at 15:20
  • That worked, thanks @eyllanesc Commented May 9, 2018 at 15:23
  • 2
    Or use os.path.join, so it still works if your directory name ends in a slash or back slash. Commented May 9, 2018 at 15:24
  • 2
    You can also glob recursively: glob.glob('dir*/*.xls*'). If it works from the command-line, it works in Python. Commented May 9, 2018 at 15:25
  • 1
    you can use os.walk Commented May 9, 2018 at 15:35

1 Answer 1

4

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.