专业编程基础技术教程

网站首页 > 基础教程 正文

Python 列出目录中的所有文件(python列出当前文件夹所有文件)

ccvgpt 2024-07-19 12:52:28 基础教程 57 ℃

Python 列出目录中的所有文件

8 分钟阅读

使用各种 Python 方法来列出目录中的所有文件,例如 、glob() 和递归函数。每种方法都包含一个不言自明的示例,以便您轻松掌握它们。最后,你会发现一个表格,比较这些方法,并建议哪个最合适。os.walk()os.listdir()os.scandir()

Python 列出目录中的所有文件(python列出当前文件夹所有文件)

类似地,Python 的 Glob 模块有一个 glob() 方法,用于检查当前目录中的指定文件。但是还有更深入地了解列出目录中所有文件的每种方法。

列出目录中所有文件的 Python 方法

在这里,我们将演示帮助遍历文件系统和搜索现有文件的函数。

Os.walk() 方法

它通过自上而下或自下而上遍历目录来收集目录中存在的文件名。它返回以下三个元组:

根:仅从输入中获取文件夹。
目录:从根目录获取子
目录
文件:从给定的根目录和目录中获取所有
文件

查找目录和子目录中的所有文本文件

下面是列出给定目录和子目录中所有文件的示例 Python 代码。

import os

location = 'c:/test/temp/'
files_in_dir = []

# r=>root, d=>directories, f=>files
for r, d, f in os.walk(location):
   for item in f:
      if '.txt' in item:
         files_in_dir.append(os.path.join(r, item))

for item in files_in_dir:
   print("file in dir: ", item)

执行后,结果如下:

c:/test/temp/notes/readme.txt
c:/test/temp/release/artifact_list.txt
c:/test/temp/dist/doc/readme.txt
c:/test/temp/dist/samples/sample.txt

列出给定目录和子目录下的所有目录

检查下面的 Python 代码以查找并打印给定 .dir/subdir

import os

location = 'c:/test/temp/'

dirs_in_dir = []

# r=>root, d=>directories, f=>files
for r, d, f in os.walk(location):
   for item in d:
      if '.txt' in item:
         dirs_in_dir.append(os.path.join(r, item))

for item in dirs_in_dir:
   print("Dirs under dir: ", item)

执行后,结果如下:

c:/test/temp/notes/
c:/test/temp/release/
c:/test/temp/dist/
c:/test/temp/dist/doc/
c:/test/temp/dist/samples/

Glob.glob() 方法

很多时候,我们必须遍历目录中名称与模式匹配的文件列表。在这种情况下,Python glob 模块有助于捕获给定目录中具有特定扩展名的文件列表。

glob() 函数

此函数获取根据路径名中的给定模式过滤的文件列表。我们可以采用绝对和相对的路径名。通配符,如 * 和 ?也是允许的符号。

List all files in the current directory having “.py” extension

列出当前目录中扩展名为“.py”的所有文件

例如 – 以下 Python 代码列出了当前目录中扩展名为“.py”的所有文件。

import glob

location = 'c:/test/temp/'

fileset = [file for file in glob.glob(location + "**/*.py", recursive=True)]

for file in fileset:
    print(file)

执行后,结果如下:

c:/test/temp/notes/get_sample.py
c:/test/temp/release/test1.py
c:/test/temp/dist/doc/core.py
c:/test/temp/dist/samples/first_sample.py


获取指定目录和子目录中的所有目录

import glob

location = 'c:/test/temp/'

folderset = [folder for folder in glob.glob(location + "**/", recursive=True)]

for folder in folderset:
    print(folder)

运行上述代码后,结果如下:

c:/test/temp/notes/
c:/test/temp/release/
c:/test/temp/dist/
c:/test/temp/dist/doc/
c:/test/temp/dist/samples/

用Path.iterdir()

该函数存在于模块中。它是 Python 3.4 中较新的模块,它提供了一种更强大的方法来处理路径。该方法可用于列出目录中的文件和目录。Path.iterdir()PathlibPath.iterdir()

让我们找出这个 Python 模块如何列出目录中的文件。

from pathlib import Path

# Get a list of all the files in the current directory
files = Path().iterdir()

# Print the list of files
for file in files:
    print(file)

使用该函数os.scandir()

这也是一个相对较新的函数,它返回目录条目的生成器。如果您需要以更有效的方式循环访问目录中的文件,这可能很有用。os.scandir()

下面的 Python 代码,演示了如何使用列出目录中的所有文件。os.scandir()

import os

def list_files_with_details(directory):
    """Lists all of the files in a directory and prints some additional details about each file, such as the file size and the file type."""

    # Get a generator of directory entries
    entries = os.scandir(directory)

    # Iterate over the directory entries and print some details about each file
    for entry in entries:

        # Get the file size
        file_size = entry.stat().st_size

        # Get the file type
        file_type = entry.stat().st_mode

        # Print the file name, file size, and file type
        print(f"{entry.name}: {file_size} bytes ({file_type})")

# List the files in the current directory and print some additional details about each file
list_files_with_details(".")

此代码示例将打印当前目录中所有文件的列表,以及每个文件的文件大小和文件类型。可以修改此代码示例以打印有关所需目录中文件的任何其他信息。例如,您可以打印文件创建日期、文件的上次修改日期或文件权限。

列出目录中所有文件的 Python 递归方法

在 Python 中,要列出目录中的文件及其所有子目录,我们可以使用递归函数。以下函数将以递归方式列出目录中的所有文件及其所有子目录:

import os

def list_files_recursively(directory):
    """Lists all of the files in a directory and all of its subdirectories, recursively."""

    files = []

    # Iterate over the files and directories in the directory
    for entry in os.scandir(directory):

        # If the entry is a directory, recursively list the files in that directory
        if entry.is_dir():
            files += list_files_recursively(entry.path)

        # If the entry is a file, add it to the list of files
        elif entry.is_file():
            files.append(entry.path)

    return files

# Get a list of all the files in the current directory and all of its subdirectories
files = list_files_recursively(".")

# Print the list of files
for file in files:
    print(file)

比较不同的方法

下表比较了所有方法,它们的性能,如何决定选择哪种方法以及哪种方法最好:

方法

性能

如何选择

最适合

os.listdir()

简单高效

如果您只需要列出目录中的文件

一般用途

Pathlib.Path.iterdir()

比os.listdir()

如果您需要使用模块的更高级功能,例如处理符号链接Pathlib

使用路径

glob.glob()

功能强大且灵活,可根据模式列出文件

当您需要根据模式列出文件时,例如目录中的所有 Python 文件

模式匹配

os.scandir()

比循环访问目录中的文件更有效os.listdir()

如果您需要以更有效的方式循环访问目录中的文件

循环访问文件

os.walk()

递归列出目录中的文件和目录及其所有子目录

当您需要列出目录中的文件和目录及其所有子目录时

具有自定义逻辑的递归列表

递归函数

可用于列出目录中的文件及其所有子目录

如果需要列出目录中的文件及其所有子目录,并且希望更好地控制递归

具有自定义逻辑的递归列表

这些方法的性能将取决于目录中的文件数和搜索模式的复杂性。通常,该函数将最有效地遍历目录中的文件。它通过避免不必要的系统调用和缓存文件信息来实现此目的。os.scandir()

模块的性能将取决于搜索模式的复杂性。如果搜索模式很简单,那么它会相对较快。glob

结论

有很多方法可以在 Python 中列出目录中的文件。最佳使用方法将取决于您的特定需求。

  • 如果需要列出目录中的文件及其所有子目录,则可以使用该方法。
  • 当您需要根据模式列出目录中的文件时,可以使用该模块。
  • 如果需要以更有效的方式循环访问目录中的文件,则可以使用该函数。os.listdir()os.walk()globos.scandir()

Tags:

最近发表
标签列表