Python3在指定路径下递归定位文件中出现的字符串

简介: [本文出自天外归云的博客园] 脚本功能:在指定的路径下递归搜索,找出指定字符串在文件中出现的位置(行信息)。 用到的python特性: 1. PEP 318 -- Decorators for Functions and Methods 2.

[本文出自天外归云的博客园]

脚本功能:在指定的路径下递归搜索,找出指定字符串在文件中出现的位置(行信息)。

用到的python特性:

1. PEP 318 -- Decorators for Functions and Methods

2. PEP 380 -- Syntax for Delegating to a Subgenerator

3. PEP 471 -- os.scandir() function -- a better and faster directory iterator

4. PEP 498 -- Literal String Interpolation

代码如下:

import os
import sys

__all__ = ['DirPath']

'''
    在指定路径下递归查找包含指定字符串的文件
    可以指定查找的文件类型category-默认为'.py'
    可以指定查找的字符串str-默认为'python'
'''


class DirPath(object):
    # 初始化参数查找路径-path
    def __init__(self, path):
        self.show = self.show()
        self.path = path

    # 开启func协程的装饰器
    def on(func):
        def wrapper(*args):
            res = func(*args)
            next(res)
            return res

        return wrapper

    @on
    # 搜索path路径下的python文件
    def search(self, target, category):
        while True:
            path = yield
            for entry in os.scandir(path):
                if entry.is_file():
                    if entry.name.endswith(category):
                        target.send(entry.path)
                if entry.is_dir():
                    self.search(target, category).send(entry.path)

    @on
    # 找到f文件中包含str的行信息并发送给target
    def find_str(self, target, str):
        while True:
            path = yield
            with open(path, "r", encoding='utf-8') as f:
                for (name, value) in enumerate(f):
                    if str in value:
                        target.send(f"[{path}][{name+1}]:{value}")

    @on
    # 展示查询结果
    def show(self):
        while True:
            res = yield
            print(res)

    # 默认在'.py'类型文件中查找字符串-可以指定文件类型category
    # 默认查找字符串'python'-可以指定查找字符串str
    def code_search(self, category=".py", str="python"):
        self.search(self.find_str(self.show, str), category).send(self.path)


if __name__ == '__main__':
    path = sys.argv[1]
    Dir = DirPath(path)
    Dir.code_search(str=sys.argv[2], category=sys.argv[3])

本地运行脚本,搜索结果示例如下:

相关文章
|
4月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
410 1
|
4月前
|
数据可视化 Linux iOS开发
Python脚本转EXE文件实战指南:从原理到操作全解析
本教程详解如何将Python脚本打包为EXE文件,涵盖PyInstaller、auto-py-to-exe和cx_Freeze三种工具,包含实战案例与常见问题解决方案,助你轻松发布独立运行的Python程序。
1252 2
|
4月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
363 100
|
4月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
501 99
|
4月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
4月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
4月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
4月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
3月前
|
存储 Java 索引
(Python基础)新时代语言!一起学习Python吧!(二):字符编码由来;Python字符串、字符串格式化;list集合和tuple元组区别
字符编码 我们要清楚,计算机最开始的表达都是由二进制而来 我们要想通过二进制来表示我们熟知的字符看看以下的变化 例如: 1 的二进制编码为 0000 0001 我们通过A这个字符,让其在计算机内部存储(现如今,A 字符在地址通常表示为65) 现在拿A举例: 在计算机内部 A字符,它本身表示为 65这个数,在计算机底层会转为二进制码 也意味着A字符在底层表示为 1000001 通过这样的字符表示进行转换,逐步发展为拥有127个字符的编码存储到计算机中,这个编码表也被称为ASCII编码。 但随时代变迁,ASCII编码逐渐暴露短板,全球有上百种语言,光是ASCII编码并不能够满足需求
196 4
|
3月前
|
监控 机器人 编译器
如何将python代码打包成exe文件---PyInstaller打包之神
PyInstaller可将Python程序打包为独立可执行文件,无需用户安装Python环境。它自动分析代码依赖,整合解释器、库及资源,支持一键生成exe,方便分发。使用pip安装后,通过简单命令即可完成打包,适合各类项目部署。

推荐镜像

更多