Python 如何列出目录的内容

Python 如何列出目录的内容

计算机的文件系统的目录是一个用于存储和定位文件的组织特征。通过将目录进行层次化组织,创建了目录的树形结构。目录之间存在父子关系。文件夹也可以用来指代目录。随着时间的推移,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和recursive flag这两个参数:

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

它递归地搜索当前目录的所有子目录中的所有文件。recursive标志的默认设置为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(‘路径’)构造目录的路径。
  • 接下来,使用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')]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程