如何在 Python 中列出目录的内容?

programmingpythonserver side programming更新于 2023/12/11 10:40:00

计算机文件系统的目录是用于存储和定位文件的组织功能。目录树是通过按层次结构组织目录创建的。目录中存在父子关系。文件夹也可用于引用目录。随着时间的推移,Python 积累了许多可以列出目录内容的 API。有用的函数包括 Path.iterdir、os.scandir、os.walk、Path.rglob 和 os.listdir。

我们可能需要在 Python 中列出给定目录中的文件或文件夹。您可以通过多种方式实现此目的。

OS 模块

Python 的 OS 模块中提供了一个返回目录中文件或文件夹列表的函数。

使用 Python 操作系统库列出目录中的文件。目录中的每个文件和文件夹均由 Python os.listdir() 方法列出。函数 os.walk() 返回整个文件树中所有文件的列表。

使用 Python OS 库有几种方法可以列出目录中的文件。

本文将介绍如何使用 os.listdir() 获取目录中的文件和文件夹。

使用 os.listdir() 方法

Python 中的 os.listdir() 方法显示指定目录中所有文件和文件夹的列表。操作系统采用特殊条目,如"。"和".."在各个目录之间进行遍历,但此方法不会返回这些目录。

此外,os.listdir() 不会返回第一级目录上方的文件和文件夹。换句话说,os.listdir() 不会返回该方法找到的子文件夹中的任何内容。您要从中检索其文件和文件夹名称的目录的文件路径是 os.listdir() 函数接受的唯一参数。

语法

os.listdir(path)

示例

以下是使用 os.listdir() 方法列出目录内容的示例 -

# importing the module import os # Providing the path of the directory path = 'D:\Work TP' # Retrieving the list of all the files folders = os.listdir(path) # loop to iterate every item in the list for s in folders: print(s)

输出

以下是上述代码的输出 -

moving files.py
mysql_access.py
stored procedure python-sql.py
trial.py

使用 os.walk() 方法

使用 os.walk() 函数可获得树中包含的文件列表。该技术将迭代树中的每个目录。

然后,os.walk() 将返回目录及其子目录中包含的所有文件和文件夹的名称。

语法

os.walk(topdown)

topdown 表示设置为 True 时应从上向下扫描目录。如果此值为 False(可选),则将从下向上扫描目录。

示例

以下是使用 os.walk() 方法列出目录内容的示例:

# importing the module import os # Providing the path path = 'D:\Work TP' # loop for retrieving all the files and folders for top-down search for root, directories, contents in os.walk(path, topdown=False): # joining together the root folder where the directory exists of every files along with its name for name in contents: print(os.path.join(root, name)) for name in directories: print(os.path.join(root, name))

输出

以下是上述代码的输出 -

D:\Work TP\SubDirectory\How to copy files from one folder to another using Python.docx
D:\Work TP\SubDirectory\How to create an empty file using Python.docx
D:\Work TP\SubDirectory\Sarika Sample Articles (Python-MySQL Procedures).docx
D:\Work TP\SubDirectory\sql python create table.docx
D:\Work TP\moving files.py
D:\Work TP\mysql_access.py
D:\Work TP\stored procedure python-sql.py
D:\Work TP\trial.py
D:\Work TP\SubDirectory

使用 os.scandir() 方法

Scandir 使用与 listdir 相同的目录迭代系统调用来获取指定路径上的文件的名称,但它在两个方面与 listdir 不同。

  • 与纯文件名字符串不同,返回的是轻量级的 DirEntry 对象,它保存文件名字符串并提供简单的方法来检索操作系统可能返回的任何其他数据。
  • scandir 不会立即返回整个列表,而是通过返回生成器(而不是列表)来充当真正的迭代器。

对于路径中的每个文件和子目录,scandir() 返回一个 DirEntry 对象。

示例

以下是使用 os.scandir() 方法列出目录内容的示例 -

# importing the modules import os # getting all the files present inside a specific folder dir_track = r'D:\Work TP' for track in os.scandir(dir_track): if track.is_file(): print(track.name)

输出

以下是上述代码的输出 -

moving files.py
mysql_access.py
stored procedure python-sql.py
trial.py

glob 模块

Python glob 模块允许我们搜索所有路径名,以找到符合给定模式的文件。Unix shell 建立的规则用于定义所提供的文件匹配模式。

软件的输出返回按照这些准则以随机顺序匹配特定模式文件所获得的结果。由于 glob 模块可以浏览本地磁盘中特定位置的文件列表,因此在使用文件匹配模式时我们必须满足某些要求。该模块将主要浏览仅遵循特定模式的文件的磁盘列表。

使用 glob() 递归搜索文件

路径名和递归标志是此函数所需的两个参数:

  • pathname− 相对或绝对(包括文件名和完整路径)(使用 UNIX shell 样式的通配符)。通过为 glob() 方法提供绝对路径或相对路径,我们可以进行文件搜索。具有完整目录结构的路径名称为绝对路径。相对路径是包含目录名以及一个或多个通配符的路径名。
  • recursive − 如果设置为 True,将执行递归文件搜索。它以递归方式搜索当前目录子目录中的所有文件。递归标志的默认设置为 False。这意味着它只会查看我们的搜索路径中列出的文件夹。

它以递归方式搜索当前目录子目录中的所有文件。递归标志的默认设置为 False。这意味着它只会查找我们搜索路径中列出的文件夹。

语法

glob.glob(pathname, *, recursive=False)

示例

以下是使用 glob.glob() 方法使用绝对路径列出目录内容的示例:

import glob # relative path for searching all the python files contents = glob.glob("D:\Work TP\*.py",recursive=True) print(contents)

输出

以下是上述代码的输出 -

['D:\Work TP\moving files.py', 'D:\Work TP\mysql_access.py', 'D:\Work TP\stored procedure python-sql.py', 'D:\Work TP\trial.py']

使用 iglob() 循环遍历文件

iglob() 和 glob() 之间的唯一区别是前者提供了一个符合模式的文件名迭代器。该方法生成一个迭代器对象,我们可以循环遍历该对象以获取各个文件的名称。

语法

glob.iglob(pathname,*,recursive=False)

实际上不将所有项目存储在一起,而是返回一个产生与 glob() 相同值的迭代器。

调用时,iglob() 会生成一个可调用对象,将结果加载到内存中。

示例

以下是使用 glob.iglob() 方法列出目录内容的示例 -

# importing the module import glob # providing the path glob.iglob('D:\Work TP/*.py') # iterating over the files in that path of directory for items in glob.iglob('D:\Work TP/*.py'): print(items)

输出

以下是上述代码的输出 -

D:\Work TP\moving files.py
D:\Work TP\mysql_access.py
D:\Work TP\stored procedure python-sql.py
D:\Work TP\trial.py

Pathlib 模块

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

  • import pathlib− 对于许多操作系统,Pathlib 模块提供类和方法来管理文件系统路径并检索与文件相关的数据。
  • 接下来使用 pathlib.Path('path') 构造目录的路径。
  • 接下来,使用 iterdir() 遍历目录中的每个条目。
  • 最后,使用 path.isfile() 函数确定当前元素是否为文件。

示例

以下是使用 pathlib 模块列出目录内容的示例 -

# importing the module import pathlib # path of the directory dir_path = r'D:\Work TP' # storing the file names res = [] # constructing the path object d = pathlib.Path(dir_path) # iterating the directory for items in d.iterdir(): # checking if it's a file if items.is_file(): res.append(items) print(res)

输出

以下是上述代码的输出 -

[WindowsPath('D:/Work TP/moving files.py'), WindowsPath('D:/Work TP/mysql_access.py'), WindowsPath('D:/Work TP/stored procedure python-sql.py'), WindowsPath('D:/Work TP/trial.py')]

相关文章