将txt转xml python
时间: 2023-09-04 07:13:43 浏览: 99
你可以使用Python的`xml.etree.ElementTree`库来将文本(txt)转换为XML格式。以下是一个简单的示例代码:
```python
import xml.etree.ElementTree as ET
def txt_to_xml(txt_file, xml_file):
# 创建根元素
root = ET.Element("data")
# 打开文本文件并逐行读取内容
with open(txt_file, 'r') as file:
lines = file.readlines()
# 创建XML元素并添加到根元素中
for line in lines:
# 去除换行符
line = line.strip()
# 创建子元素
element = ET.SubElement(root, "line")
element.text = line
# 创建XML树并写入XML文件
tree = ET.ElementTree(root)
tree.write(xml_file)
# 指定输入的txt文件和输出的xml文件路径
txt_file = "input.txt"
xml_file = "output.xml"
# 调用函数进行转换
txt_to_xml(txt_file, xml_file)
```
在上面的示例代码中,我们通过`txt_to_xml`函数将输入的文本文件转换为XML文件。首先,我们创建了一个根元素(`data`),然后打开文本文件并逐行读取内容。对于每一行,我们创建一个子元素(`line`),并将其添加到根元素中。最后,我们使用`ElementTree`的`write`方法将XML树写入到指定的XML文件。
你可以将上述代码保存到一个Python脚本中(例如`txt_to_xml.py`),然后在命令行中运行该脚本,指定输入的txt文件路径和输出的xml文件路径。请确保在运行脚本之前,安装了Python的`xml.etree.ElementTree`库。