zoukankan      html  css  js  c++  java
  • 通过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:	est', 'world')
    ['D:\test\\file1\\3.txt', 'D:\test\\file1\\file3\\5.txt']
    
  • 相关阅读:
    [翻译] Blocks and Variables
    UIView独占响应事件
    iOS中block类型大全
    Erlang入门(二)—并发编程
    Erlang入门(一)
    学习Erlang--1、入门
    一位Erlang程序员的自白
    安装ejabberd2并配置MySQL为其数据库
    JDBC 与ODBC的区别
    ejabberd的多域名(domain)设置
  • 原文地址:https://www.cnblogs.com/bill-h/p/14602052.html
Copyright © 2011-2022 走看看