根据ETL报错的信息,用Python从源文件中提取出错误的内容

这段Python代码用于从源文件中提取出错误行的内容。它首先读取包含错误行号的文件,然后将这些行号转换为整数,最后在源文件中找到对应的行并将其写入新的文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding:utf-8 -*-
#标准代码
import linecache
#lines存储错误的行
lines=[]        #错误行,字符串形式列表
error_lines=[]  #错误行,不包括首行
int_lines=[]    #错误行,整数形式列表,不包括首行
error_lines_file_path=r'C:\Users\yawei.chen\Desktop\Puck\Python\Job\test\error_seq.txt' #需要抽取的错误行数
source_file_path=r'C:\Users\yawei.chen\Desktop\Puck\Python\Job\test\iclog100.y2018.d0513.s00001.20180513002906.txt'#源文件
extract_file_path=r"C:\Users\yawei.chen\Desktop\IM22407681.txt"   #抽取的错误行文件,存储位置和文件名

#可控制函数
def truncate_file(error_lines_file_path,source_file_path,extract_file_path):
    # 读取错误的行数,并输出到error_lines
    with open(error_lines_file_path, "r", encoding='utf-8') as y:
        for line in y:
            lines.append(line)
            error_lines = lines[2:len(lines) + 1]

        # 生成int_lines,将error_lines中的字符串转换成int格式
        for int_line in error_lines:
            int_lines.append(int(int_line))

    # 在源文件中,提取错误行的内容
    with open(source_file_path, 'r', encoding='utf-8') as f1, \
            open(extract_file_path, 'w', encoding='utf-8') as f2:
        # 将错误行写入到extract_file_path文件中
        for int_line in int_lines:
            count = linecache.getline(source_file_path, int_line)
            f2.write(count)

truncate_file(error_lines_file_path,source_file_path,extract_file_path)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值