Python脚本小工具之文件与内容搜索

文章介绍了一个在Linux环境下使用Python编写的脚本,该脚本能实现查找指定目录下的所有文件、按文件名过滤以及在文件内容中搜索特定文本的功能。它适用于纯文本文件,不支持Word、Excel等格式。
摘要由CSDN通过智能技术生成

 目录

一、前言 

二、代码

三、结果


一、前言 

    ​日常工作中,经常需要在指定路径下查找指定类型的文件,或者是指定内容的查找,在window环境中,即可以使用一些工具如notepad或everything,也可以使用python脚本。但在linux环境下,则需用python脚本

二、代码

    ​代码中定义一个类包含3个函数

listDir:查找指定目录下的所有文件,包含子目录下的文件,返回包含文件名和路径组成的字典

flisttype:在指定目录下查找文件名包含指定名称的文件,返回文件名和对应的路径的字典

fcontfind:文件内容查找,返回包含指定内容文件的路径,输入为需查找文件组成的列表fdict和需查找的内容cont

import os
"""内容的查找只能针对纯文本文档,对word、excel之类的文件无效"""
class file_content_search:
    def __init__(self):
        self.allfile={}
        self.typefile = {}
        self.contfile=[]
    #查找指定目录下的所有文件,包含子目录下的文件,返回包含文件名和路径组成的字典
    def listDir(self,rootDir):
        for filename in os.listdir(rootDir):
            pathname = os.path.join(rootDir, filename)
            pathname =pathname.replace("\\","/")    #将双斜杠变成单斜杠,双斜杠路径无效
            if (os.path.isfile(pathname)):
                self.allfile[filename]=pathname
            else:
                self.listDir(pathname)
        return(self.allfile)
    #在指定目录下查找文件名包含指定名称的文件,返回文件名和对应的路径的字典
    def flisttype(self,allfile1,listtype):
        for ftype in listtype:
            for fname,fpath in allfile1.items():
                if ftype in fname:
                    self.typefile[fname]=fpath
        return(self.typefile)

    #文件内容查找,返回包含指定内容文件的路径,输入为需查找文件组成的列表fdict和需查找的内容cont
    def fcontfind(self,fdict,cont):
        for fname,fpath in fdict.items():
            with open(fpath, "r",encoding="gbk",errors="ignore") as f:
                content = f.read()
                result = content.find(cont)
                if result != -1:
                    print("Found at index", result)
                    self.contfile.append(fpath)
                # else:
                #     print("Not found,")
        return(self.contfile)
if __name__=="__main__":
    file_path=r"C:\Users\Administrator\Desktop\计划"
    file_find=file_content_search()   #类实例化
    file_result=file_find.listDir(file_path)
    print(file_result)
    type = ["txt"]    #指定查找的文件类型
    ftype_find=file_find.flisttype(file_result,type)  #使用上一个函数listDir中返回的文件列表
    print(ftype_find)
    cont="生活"       #指定查找的内容
    fcont_find=file_find.fcontfind(ftype_find,cont)
    print(fcont_find)

三、结果

文件查找

 

查找xmind文件

 

查找txt文件包含“生活”的文件

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值