Python基础入门 Day84 文件的搜索与查找

81次阅读
没有评论

共计 2247 个字符,预计需要花费 6 分钟才能阅读完成。

在处理大量文件时,我们可能需要查找符合某种条件的文件。例如,查找某个目录下所有 .txt 文件,或者查找包含特定内容的文件。Python 提供了多种方法来实现文件的搜索与查找,包括 os 模块、glob 模块以及 fnmatch 模块等。

  1. 使用 os.walk() 递归查找文件
    os.walk() 可以遍历指定目录下的所有文件和子目录,适合递归查找文件。
import os

def find_files_by_extension(folder_path, extension):
    result = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(extension):
                result.append(os.path.join(root, file))
    return result

# 查找所有 .txt 文件
files = find_files_by_extension("/path/to/directory", ".txt")
print(files)

此方法会遍历目录中的每个子目录,找到所有符合扩展名的文件。

  1. 使用 glob 模块进行简单模式匹配
    glob 模块可以通过通配符匹配文件路径,比 os.walk() 更简洁。
import glob

# 查找所有 .txt 文件
files = glob.glob("/path/to/directory/*.txt")
print(files)

# 查找子目录中的所有 .txt 文件
files = glob.glob("/path/to/directory/**/*.txt", recursive=True)
print(files)

glob 使用通配符来匹配文件路径,** 表示递归查找子目录。

  1. 使用 fnmatch 模块进行文件名匹配
    fnmatch 模块提供了类似 Unix Shell 的文件名匹配功能,用于在文件列表中匹配文件。
import fnmatch
import os

def find_files_with_pattern(folder_path, pattern):
    result = []
    for root, dirs, files in os.walk(folder_path):
        for file in fnmatch.filter(files, pattern):
            result.append(os.path.join(root, file))
    return result

# 查找所有以 "data" 开头的文件
files = find_files_with_pattern("/path/to/directory", "data*.txt")
print(files)

fnmatch.filter() 会返回符合模式的文件名。常用的通配符有 *?[]

  1. 查找包含特定内容的文件
    有时我们不仅仅根据文件名来查找文件,而是根据文件的内容进行查找。例如,查找所有包含某个关键词的文件:
def find_files_containing_keyword(folder_path, keyword):
    result = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                with open(file_path, "r", encoding="utf-8") as f:
                    if keyword in f.read():
                        result.append(file_path)
            except:
                continue  # 忽略无法读取的文件(如二进制文件)return result

# 查找包含 "python" 关键字的文件
files = find_files_containing_keyword("/path/to/directory", "python")
print(files)

此方法会检查每个文件的内容,找到包含特定关键词的文件。

  1. 结合使用多个条件进行查找
    我们可以同时根据文件名和文件内容来筛选文件:
def find_files_by_name_and_content(folder_path, pattern, keyword):
    result = []
    for root, dirs, files in os.walk(folder_path):
        for file in fnmatch.filter(files, pattern):
            file_path = os.path.join(root, file)
            try:
                with open(file_path, "r", encoding="utf-8") as f:
                    if keyword in f.read():
                        result.append(file_path)
            except:
                continue
    return result

# 查找所有包含 "python" 关键字的 .txt 文件
files = find_files_by_name_and_content("/path/to/directory", "*.txt", "python")
print(files)

总结:
通过使用 os.walk()globfnmatch 等模块,我们可以非常灵活地查找符合条件的文件。对于需要根据文件内容进行筛选的场景,我们可以打开文件并读取内容进行匹配。

练习与思考:

  1. 编写一个程序,查找指定目录下所有 .log 文件,并统计每个文件的行数。
  2. 修改程序,查找包含 "error" 或 "warning" 的日志文件,并输出文件路径。
  3. 使用 glob 查找所有 .md 文件,并将它们移动到 docs 目录中。
正文完
 0
评论(没有评论)