17370845950

Python 递归读取目录中所有文件内容
答案:Python中递归读取目录所有文件内容可用os.walk()或pathlib.Path.rglob()方法,前者通过三元组遍历目录,后者语法更简洁;需注意文件编码、类型及大文件内存问题,建议按需选择文本或二进制模式读取。

Python 递归读取目录中所有文件内容

在 Python 中,可以使用 os.walk()pathlib.Path.rglob() 来递归遍历目录并读取所有文件的内容。下面介绍两种常用方法,适用于不同场景。

1. 使用 os.walk() 遍历并读取文件内容

os.walk() 是传统且高效的方式,能够递归进入子目录,返回目录路径、子目录名和文件名。

import os

def read_all_files_with_os_walk(root_dir): for dirpath, dirnames, filenames in os.walk(root_dir): for filename in filenames: file_path = os.path.join(dirpath, filename) try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() print(f"--- 内容来自: {file_path} ---") print(content) except Exception as e: print(f"无法读取文件 {file_path}: {e}")

调用方式:

read_all_files_with_os_walk("/your/directory/path")

2. 使用 pathlib.Path.rglob() 更简洁的写法

pathlib 是 Python 3.4+ 推荐的路径操作模块,rglob() 可直接匹配所有符合条件的文件,语法更直观。

from pathlib import Path

def read_all_files_with_pathlib(root_dir): root_path = Path(root_dir)

匹配所有文件(可改为特定后缀如 "*.txt")

for file_path in root_path.rglob("*"):
    if file_path.is_file():
        try:
            content = file_path.read_text(encoding='utf-8')
            print(f"--- 内容来自: {file_path} ---")
            print(content)
        except Exception as e:
            print(f"无法读取文件 {file_path}: {e}")

调用方式:

read_all_files_with_pathlib("/your/directory/path")

3. 注意事项与建议

  • 某些文件可能不是文本文件(如图片、二进制文件),使用 read_text()open(..., 'r') 会报错,必要时可用二进制模式判断或跳过。
  • 指定编码很重要,utf-8 覆盖大多数情况,但遇到 gbk 等中文编码文件时需调整。
  • 若只想读取特定类型文件,可修改匹配模式,例如:root_path.rglob("*.py") 只读取 Python 文件。
  • 大文件建议逐行读取(如使用 for line in f)避免内存溢出。

基本上就这些,根据需求选择合适的方法即可。