如何在 Python 中查找目录中所有扩展名为 .txt 的文件?


在目录中搜索特定文件是一项可以使用 Python 工具轻松完成的任务;在某些情况下,您可能需要使用 Python 查找目录中所有扩展名为 .txt 的文件。让我们深入探讨此任务中涉及的过程,并向您展示如何使用易于理解的代码示例以及解释来实现此查找目录中所有扩展名为 .txt 的文件的任务的不同方法。

使用 os.listdir()

在此代码示例中,我们首先导入 os 模块,该模块对于在 Python 中处理目录和文件至关重要。

示例

find_txt_files() 函数以 directory_path 作为其参数;directory_path 表示您希望搜索的目录的路径。

我们使用 os.listdir(directory_path) 获取所有项目(即指定目录中的文件和目录)的列表。

通过对每个项目进行迭代并使用 os.path.isfile() 检查它是否为文件,我们确保我们只考虑文件而不是目录。

在第二个条件中,我们使用 item.endswith('.txt') 来仅检索扩展名为 .txt 的文件。

该函数输出在目录中找到的文本文件的列表。

import os

def find_txt_files(directory_path):
   try:
      # Use os.listdir() to obtain a list of all items in the directory
      all_items = os.listdir(directory_path)

      # Filter out only the files with '.txt' extension
      txt_files = [item for item in all_items if 
os.path.isfile(os.path.join(directory_path, item)) and item.endswith('.
txt')]

      return txt_files

   except FileNotFoundError:
      print(f"Error: The directory '{directory_path}' does not exist.")
      return []

# Replace 'directory_path' with the path of the directory you want to 
search
directory_path = '/path/to/your/directory'
txt_files_list = find_txt_files(directory_path)

if txt_files_list:
   print("Text files in the directory:")
   for file_name in txt_files_list:
      print(file_name)
else:
   print("No .txt files found in the directory.")

输出

对于某个目录,获得了以下输出

Text files in the directory:
fubar.txt

使用 os.listdir()

示例

在本例中,我们首先导入 os 模块,该模块使我们能够与操作系统、目录和文件进行交互。

find_txt_files() 函数接受 directory_path 作为其参数。directory_path 表示您希望搜索 .txt 文件的目录的路径。

部署 os.listdir(directory_path) 函数以获取所有项目的列表,即指定目录中的文件和目录。

通过迭代每个项目并使用 os.path.isfile() 检查它是否为文件,我们确保我们只考虑文件并忽略目录。

在第二个实例中,我们部署 item.endswith('.txt') 以仅查找扩展名为 .txt 的文件。

发现该函数返回在目录中找到的 .txt 文件的列表。

import os

def find_txt_files(directory_path):
   try:
      # Get a list of all items (files and directories) in the specified 
directory
      all_items = os.listdir(directory_path)

      # Filter out only the files with the '.txt' extension
      txt_files = [item for item in all_items if os.path.isfile(os.path.
join(directory_path, item)) and item.endswith('.txt')]

      return txt_files

   except FileNotFoundError:
      print(f"Error: The directory '{directory_path}' does not exist.")
      return []
# Replace 'directory_path' with the path of the directory you want to 
search
directory_path = '/path/to/your/directory'
txt_files_list = find_txt_files(directory_path)

if txt_files_list:
   print("Text files in the directory:")
   for file_name in txt_files_list:
      print(file_name)
else:
   print("No .txt files found in the directory.")

输出

对于某个目录,获得了以下输出

Text files in the directory:
fubar.txt

使用 os.scandir() 提高效率

示例

这里,os.listdir() 被 os.scandir() 替换,以便提供一种更有效的方式来列出目录中的文件。

当 os.scandir(directory_path) 的输出用作条目列表时,会创建一个上下文管理器,该管理器可以有效地迭代目录条目,并且无需在之后显式关闭目录。

通过使用 entry.is_file(),检查每个条目是否为文件,如果发现是文件,则继续检查它是否以 .txt 结尾。

发现该函数返回在目录中找到的 .txt 文件的列表。

import os

def find_txt_files(directory_path):
   try:
      # Use os.scandir() for a more efficient listing
      with os.scandir(directory_path) as entries:
         txt_files = [entry.name for entry in entries if entry.is_file() 
and entry.name.endswith('.txt')]

      return txt_files

   except FileNotFoundError:
      print(f"Error: The directory '{directory_path}' does not exist.")
      return []
# Replace 'directory_path' with the path of the directory you want to 
search
directory_path = '/path/to/your/directory'
txt_files_list = find_txt_files(directory_path)

if txt_files_list:
   print("Text files in the directory:")
   for file_name in txt_files_list:
      print(file_name)
else:
   print("No .txt files found in the directory.")

输出

对于某个目录,获得了以下输出

Text files in the directory:
fubar.txt

使用 os.walk() 进行递归搜索

示例

在此特定示例中,我们使用 os.walk() 来实现对 .txt 文件的递归搜索,包括子目录。

然后 os.walk(directory_path) 函数返回一个生成器,该生成器继续提供包含根目录、子目录和该目录中文件的元组。

迭代每个元组,对于 files 列表中的每个文件,我们部署 file.endswith('.txt') 来查找它是否以 .txt 扩展名结尾。

如果它确实以该扩展名结尾,我们使用 os.path.join(root, file) 构造完整的文件路径,并将该文件添加到 txt_files 列表中。

该函数最终返回在目录及其子目录中找到的 .txt 文件的完整列表。

import os

def find_txt_files(directory_path):
   try:
      # Use os.walk() to get a recursive listing of all files
      txt_files = []
      for root, dirs, files in os.walk(directory_path):
         for file in files:
            if file.endswith('.txt'):
               txt_files.append(os.path.join(root, file))

      return txt_files

   except FileNotFoundError:
      print(f"Error: The directory '{directory_path}' does not exist.")
      return []
# Replace 'directory_path' with the path of the directory you want to 
search
directory_path = '/path/to/your/directory'
txt_files_list = find_txt_files(directory_path)

if txt_files_list:
   print("Text files in the directory:")
   for file_name in txt_files_list:
      print(file_name)
else:
   print("No .txt files found in the directory.")

输出

对于某个目录,获得了以下输出

Text files in the directory:
/content/foo/fubar.txt

使用 pathlib.Path() 进行现代列表

示例

在这个最后的示例中,我们采用最新且现代的方法来执行相同的列表任务,方法是使用 pathlib.Path()。

我们最初从 pathlib 模块导入 Path;此模块为处理目录和文件提供了一个面向对象的接口。

通过 Path(directory_path) 创建一个指向指定目录的 Path 对象。

通过使用 path.iterdir() 获取目录中包含文件和目录的所有条目的迭代器。

file.is_file() 函数用于检查每个条目是否为文件,如果它确实是一个文件,我们使用 file.suffix 检查它是否具有 .txt 后缀。

如果满足所有这些条件,则将文件包含在 txt_files 列表中。

然后发现该函数返回在目录中找到的 .txt 文件的列表。

from pathlib import Path

def find_txt_files(directory_path):
    try:
        # Use pathlib.Path() for modern file listing
        path = Path(directory_path)
        txt_files = [file for file in path.iterdir() 
if file.is_file() and file.suffix == '.txt']

        return txt_files

    except FileNotFoundError:
        print(f"Error: The directory '{directory_path}' 
does not exist.")
        return []
# Replace 'directory_path' with the path of the 
directory you want to search
directory_path = '/path/to/your/directory'
txt_files_list = find_txt_files(directory_path)

if txt_files_list:
    print("Text files in the directory:")
    for file_name in txt_files_list:
        print(file_name)
else:
    print("No .txt files found in the directory.")

输出

对于某个目录,获得了以下输出

Text files in the directory:
/content/foo/fubar.txt

您命名它,您就可以得到它——四种使用 Python 在目录中查找所有扩展名为 .txt 的文件的多样且高效的方法。您始终可以选择多种方法中的一种或多种,例如经典的 os.listdir()、高效的 os.scandir()、递归的 os.walk() 或现代的 pathlib.Path(),以满足您的特定需求。在学习了这些代码示例和解释之后,您现在拥有了一个多功能工具包,可以自动化文件搜索并轻松优雅地组织您的 Python 项目。

通过练习这些简洁优雅的代码片段,您可以轻松地找到任何目录中所有扩展名为 .txt 的文件。Python 的多功能性和易用性使其成为处理与文件相关的任务的绝佳选择,无论您是在管理数据、组织文件还是处理文本文件以进行分析。

更新于: 2023-07-28

1K+ 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.