在本文中,我们将了解如何在 Python 中列出目录中的所有文件。有多种方法可以列出目录的文件。在本文中,我们将使用以下 四种方法

  • os.listdir('dir_path'):返回指定目录路径中存在的文件和目录的列表。
  • os.walk('dir_path'):递归获取目录和子目录中所有文件的列表。
  • os.scandir('path'):返回目录条目以及文件属性信息。
  • glob.glob('pattern'): glob 模块列出名称遵循特定模式的文件和文件夹。

目录




如何列出目录的所有文件



获取目录的文件列表很容易!使用os 模块的listdir()isfile()函数列出一个目录的所有文件。以下是步骤。

  1. 导入操作系统模块 这个模块帮助我们在 Python 中使用依赖于操作系统的功能。os 模块提供与操作系统交互的功能。
  2. 使用 os.listdir() 函数os.listdir('path')函数返回一个列表,其中包含由path.
  3. 迭代结果 使用for 循环迭代 listdir() 函数返回的文件。使用 for 循环,我们将迭代listdir() 函数返回的每个文件
  4. 使用 isfile() 函数 在每次循环迭代中,使用该os.path.isfile('path')函数检查当前路径是文件还是目录。如果是文件,则将其添加到列表中。如果给定路径是文件,则此函数返回 True。否则,它返回 False。




列出目录文件的示例

让我们看看如何列出“帐户”文件夹的文件。将listdir()列出当前目录中的文件并忽略子目录。

示例 1列出目录中的文件



import os

# folder path
dir_path = r'E:\\account\\'

# list to store files
res = []

# Iterate directory
for path in os.listdir(dir_path):
    # check if current path is a file
    if os.path.isfile(os.path.join(dir_path, path)):
        res.append(path)
print(res)






输出

这里我们得到了三个文件名。

['profit.txt', 'sales.txt', 'sample.txt']

如果您知道生成器表达式,则可以使用生成器函数使代码更小更简单,如下所示。

生成器表达式



import os

def get_files(path):
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path, file)):
            yield file




然后在需要时简单地调用它。



for file in get_files(r'E:\\account\\'):
    print(file)





示例 2:列出文件和目录。

直接调用listdir('path')函数获取目录的内容。



import os

# folder path
dir_path = r'E:\\account\\'

# list file and directories
res = os.listdir(dir_path)
print(res)






输出

正如您在输出中看到的,“reports_2021”是一个目录。

['profit.txt', 'reports_2021', 'sales.txt', 'sample.txt']

os.walk()列出目录和子目录中的所有文件

os.walk()函数返回一个生成器,该生成器创建一个值元组(current_path、current_path 中的目录、current_path 中的文件)。




注意:使用该os.walk()函数,我们可以列出给定目录中的所有目录、子目录和文件。

它是一个递归函数,即每次调用生成器时,它都会递归地跟随每个目录以获取文件和目录的列表,直到初始目录中没有更多的子目录可用。

例如,调用os.walk('path')将为它访问的每个目录生成两个列表。第一个列表包含文件,第二个列表包含目录。

让我们看一下列出目录和子目录中所有文件的示例。




示例



from os import walk

# folder path
dir_path = r'E:\\account\\'

# list to store files name
res = []
for (dir_path, dir_names, file_names) in walk(dir_path):
    res.extend(file_names)
print(res)



输出



['profit.txt', 'sales.txt', 'sample.txt', 'december_2021.txt']



注意:在循环中添加break以停止在子目录中递归查找文件。

示例



from os import walk

# folder path
dir_path = r'E:\\account\\'
res = []
for (dir_path, dir_names, file_names) in walk(dir_path):
    res.extend(file_names)
    # don't look inside any subdirectory
    break
print(res)






os.scandir()获取目录的文件

scandir()函数返回目录条目以及文件属性信息,为许多常见用例提供更好的性能。

它返回对象的迭代器os.DirEntry,其中包含文件名。

示例



import os

# get all files inside a specific folder
dir_path = r'E:\\account\\'
for path in os.scandir(dir_path):
    if path.is_file():
        print(path.name)






输出

profit.txt
sales.txt
sample.txt

用于列出目录文件的 Glob 模块

Python glob模块是 Python 标准库的一部分,用于 查找名称遵循特定模式的文件和文件夹




例如,要获取一个目录的所有文件,我们将使用该dire_path/*.*模式。在这里,*.*表示具有任何扩展名的文件。

阅读更多Python 列出扩展名为 txt 的目录中的文件

让我们看看如何使用 glob 模块列出目录中的文件。

示例



import glob

# search all files inside a specific folder
# *.* means file name with any extension
dir_path = r'E:\account\*.*'
res = glob.glob(dir_path)
print(res)





输出

['E:\\account\\profit.txt', 'E:\\account\\sales.txt', 'E:\\account\\sample.txt']

注意:如果要列出子目录中的文件,请将recursive属性设置为 True。

示例



import glob

# search all files inside a specific folder
# *.* means file name with any extension
dir_path = r'E:\demos\files_demos\account\**\*.*'
for file in glob.glob(dir_path, recursive=True):
    print(file)





输出

E:\account\profit.txt
E:\account\sales.txt
E:\account\sample.txt
E:\account\reports_2021\december_2021.txt

Pathlib 模块列出目录的文件

从 Python 3.4 开始,我们可以使用 pathlib 模块,它为大多数操作系统函数提供了一个包装器。

  • 导入 pathlib 模块:Pathlib 模块提供类和方法来处理文件系统路径并获取与不同操作系统的文件相关的数据。
  • 接下来,使用 pathlib.Path('path')构造目录路径
  • 接下来,使用iterdir()迭代目录的所有条目
  • path.isfile()最后,使用该函数检查当前条目是否为文件

示例



import pathlib

# folder path
dir_path = r'E:\\account\\'

# to store file names
res = []

# construct path object
d = pathlib.Path(dir_path)

# iterate directory
for entry in d.iterdir():
    # check if it a file
    if entry.is_file():
        res.append(entry)
print(res)