如何编写Python脚本以XML形式读写文本

2024-10-01 07:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个Python脚本从文本文件中读取以下文本:

"Re-integratieassistent – modelnummer rea 202"

并将其写入XML文件。你知道吗

用XML编写时的问题是使用UTF-8编码,因为它编写为:

"Re-integratieassistent  modelnummer rea 202"

"integratieassistent""modelnumber"之间缺少"-"

我该怎么解决这个问题?你知道吗

我的当前代码:

with codecs.open(file,encoding='utf-8', errors='ignore', mode="r") as curr_file:
    for line in curr_file.readlines():

        # Increment the counter because we encountered the XML start or begin elements
        #line = line.encode('utf-8')

        if line.find("<soapenv:Envelope") != -1 or line.find("</soapenv:Envelope") != -1 :
            i=i+1
        if (i == 1):
            file_i = codecs.open(inputFolder_new+"/"+filename,encoding='utf-8', mode="a")
            file_i.writelines(line)
        if (i == 3):
            file_o = codecs.open(outputFolder_new+"/"+filename, encoding='utf-8', mode="a")
            file_o.writelines(line)
        if (i == 4):
            file_i.writelines("</soapenv:Envelope>")
            file_o.writelines("</soapenv:Envelope>")

Tags: rewritelinesifmodelinexmlopenutf
1条回答
网友
1楼 · 发布于 2024-10-01 07:22:49

Python处理XML的接口分组在xmlpackage中。你知道吗

您可能需要考虑xml.etree.ElementTree来修改xml文件。你知道吗

import xml.etree.ElementTree as ET
root = ET.parse(file)

然后使用root.findall('{namespace}nodename')。或者root.find()。您可以在每个节点中循环尝试查找您感兴趣的项目。你知道吗

添加带有ET.SubElement(an_element_object, 'your element')的子元素。你知道吗

如果不知道XML文件的样子,就很难做到更精确。你知道吗

相关问题 更多 >