如何在 python 中使用 glob 指定目录?

How to specify directory using glob in python?

假设我有一个目录列表 dirs

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

在每个目录中,都有几个 excel 文件,我想获取其中的列表。如果我只使用 glob.glob("*.xls*") 这只会给我当前工作目录中的 excel 文件列表,但我想专门获取 "C:\path\to\dir1" 中的 excel 文件列表, "C:\path\to\dir2" 等

我试过了

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

但这只会生成空列表。

我在这里做错了什么?如何获取 dirs 中每个目录中的 excel 文件列表?

您可以使用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))