python报错xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 3, column 50

一、错误描述

错误很简单,就是xml里面有非法字符(有的说是编码问题),所以才导致xml文件出现错误,pypthon的xml.etree.ElementTree读取不了

我这里用记事本打开,发现是xml文件中有些地方出现了中文乱码

二、错误解决

我们可以再debug的时候看到每一行的text,我这里是已经修改过来,修改之前红框里面是中文乱码

在这里插入图片描述

我这里是把对应行的内容修改之后,再write到前面读取的xml_file = "F:\\e_1_1_4_7_0_4_1_5_49_60_0.xml"了,代码如下:

import xml.etree.ElementTree as ET
import os

xml_file = "F:\\e_1_1_4_7_0_4_1_5_49_60_0.xml"

with open(xml_file, mode='r', errors='ignore') as f:
    lines = f.readlines()
    f.close()

lines[2] = '    <folder>F</folder>\n'
lines[4]='   <path>none</path>\n'
lines[25] = '        <name>none</name>\n'
with open(xml_file, mode='w', errors='ignore') as f:
    for line in lines:
        f.write(line)
    f.close()

# input_dir='D:\\0.17SUO\\17所\e-两栖登陆舰\SAR\\'
input_dir='D:\\DATA\\'

filenames = os.listdir(input_dir)
for filename in filenames:
    if filename.endswith('.xml'):
        path = input_dir+filename
        file_front = filename[:-4]
        with open(path, mode='r', errors='ignore') as f:
            lines = f.readlines()
            f.close()
        lines[2] = '    <folder>F</folder>\n'
        lines[4]='   <path>'+file_front+'</path>\n'
        lines[25] = '        <name>none</name>\n'
        with open(path, mode='w', errors='ignore') as f:
            for line in lines:
                f.write(line)
            f.close()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值