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

时间:2022-09-02 00:22:34

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.

在这些目录中,有几个excel文件我想要得到一个列表。如果我只是使用global .glob(“*.xls*”),这只会在我当前的工作目录中给我一个excel文件列表,但是我想要在“C:\path\to\dir1”、“C:\path\到\dir2”中得到一个excel文件列表。

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?

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

1 个解决方案

#1


2  

You can use os.walk()

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

#1


2  

You can use os.walk()

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