首页 > 技术文章 > 通过Python查找目录下含有指定字符串的所有文件

bill-h 2021-03-31 16:14 原文

有时候我们需要搜索包含指定字符串的文件,例如在下图所示的目录test中(蓝色的表示目录),某些txt文件含有字符串'world'。以下代码展示了如何通过python找到这些文件。

import os

def get_files(root_path):  # 注意root_path前加上r
    '''
    获得目录root_path下(包括各级子目录)所有文件的路径
    '''
    file_list = []
    for i in os.listdir(root_path):
        path = root_path + r'\\' + i
        if os.path.isfile(path):
            file_list.append(path)
        elif os.path.isdir(path):
            files = get_files(path)
            for f in files:
                file_list.append(f)
    return file_list


def word_in_files(root_path, word):
    '''
    获得目录root_path下(包括各级子目录)所有包含字符串word的文件的路径
    '''
    file_list = get_files(root_path)
    result = []
    for path in file_list:
        if word in open(path, 'r', encoding='utf-8').read():  # 在实际中,有的文件由于编码的原因可能无法以这种方式打开
            result.append(path)
    return result

运行结果

>>>word_in_files(r'D:\test', 'world')
['D:\\test\\\\file1\\\\3.txt', 'D:\\test\\\\file1\\\\file3\\\\5.txt']

推荐阅读