Python脚本:遍历根文件夹下的所有子文件夹,查找内容中包含字符串“Hier_Level.rpt”的文件,并把文件的路径以及该字符串所在的行内容和行号,打印出来,并保存在新文本中。

这篇文章介绍了名为find_path.py的Python脚本,它在指定的根文件夹中搜索特定字符串(如Hier_Level.rpt),并将包含该字符串的文件路径、行号和行内容写入输出文件。只需修改search_string参数,即可适应不同搜索需求。
摘要由CSDN通过智能技术生成

python script:

find_path.py

import os

def search_and_save(root_folder, search_string, output_file):
    with open(output_file, 'w') as output:
        output.write("{:<50} {:<10} {}\n".format("File Path", "Line Number", "Line Content"))
        output.write("="*80 + "\n")
        
        for foldername, subfolders, filenames in os.walk(root_folder):
            for filename in filenames:
                file_path = os.path.join(foldername, filename)
                try:
                    with open(file_path, 'r', encoding='utf-8') as file:
                        for line_num, line in enumerate(file, start=1):
                            if search_string in line:
                                formatted_line = "{:<50} {:<10} {}".format(file_path, line_num, line.strip())
                                print(formatted_line)
                                output.write(formatted_line + "\n")
                except Exception as e:
                    print(f"Error reading file {file_path}: {e}")

# 设置根文件夹路径,搜索的字符串,和输出文件名
root_folder = "./"
search_string = "Hier_Level.rpt"
output_file = "dir_path.list"

# 调用函数进行搜索并保存结果
search_and_save(root_folder, search_string, output_file)

例子:

把该脚本copy到根目录中,然后把search_string =  "Hier_Level.rpt" 修改成想要查找的内容,

可以是任何字符串。

执行python find_path.py

命令行打印的结果:

dir_path.list 中的结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值