python将txt文件转换为xml
时间: 2023-12-31 08:06:33 浏览: 76
可以使用Python中的ElementTree模块将txt文件转换为xml。具体实现步骤如下:
1. 读取txt文件中的内容并分行存储到列表中。
```python
with open('file.txt', 'r') as f:
lines = f.readlines()
```
2. 创建xml文档。
```python
import xml.etree.ElementTree as ET
root = ET.Element('root')
```
3. 遍历lines列表,将每一行作为一个子元素添加到xml文档中。
```python
for line in lines:
child = ET.Element('line')
child.text = line.strip()
root.append(child)
```
4. 将xml文档写入文件中。
```python
tree = ET.ElementTree(root)
tree.write('file.xml', encoding='utf-8', xml_declaration=True)
```
完整代码如下:
```python
import xml.etree.ElementTree as ET
with open('file.txt', 'r') as f:
lines = f.readlines()
root = ET.Element('root')
for line in lines:
child = ET.Element('line')
child.text = line.strip()
root.append(child)
tree = ET.ElementTree(root)
tree.write('file.xml', encoding='utf-8', xml_declaration=True)
```