有二十个文件夹,每个文件夹下面有若干txt文件,使用python提取这些txt文件的特定字符串

import os

# 定义函数来处理单个txt文件并提取特定字符串
def extract_string(file_path):
    with open(file_path, 'r') as f:
        content = f.read()
        # 在字符串中查找特定的子字符串
        result = content.find('特定字符串')
        if result != -1:
            # 如果找到了特定字符串,返回文件路径和位置
            return f'在文件{file_path}中找到了特定字符串,位置为{result}。'
        else:
            # 如果未找到特定字符串,返回空字符串
            return ''

# 遍历所有文件夹和文件,并提取特定字符串
root_dir = '根目录路径'
for dir_name in os.listdir(root_dir):
    dir_path = os.path.join(root_dir, dir_name)
    if os.path.isdir(dir_path):
        # 如果是文件夹,遍历文件夹内的所有txt文件并处理
        for file_name in os.listdir(dir_path):
            if file_name.endswith('.txt'):
                file_path = os.path.join(dir_path, file_name)
                # 调用extract_string()函数来提取特定字符串
                result = extract_string(file_path)
                if result:
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值