通過Python查找目錄下含有指定字符串的所有文件


有時候我們需要搜索包含指定字符串的文件,例如在下圖所示的目錄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']


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM