我有一个充满字母数字的文本文件。我正在使python脚本从每一行获取数据并追加到变量并将该变量添加到XML。 XML将文件名添加到字母数字。但是,它无法识别数据。的错误状态
Traceback (most recent call last):
File "./xml.py", line 13, in <module>
fn.text = values
File "src/lxml/etree.pyx", line 1018, in lxml.etree._Element.text.__set__
File "src/lxml/apihelpers.pxi", line 710, in lxml.etree._setNodeText
File "src/lxml/apihelpers.pxi", line 698, in lxml.etree._createTextNode
File "src/lxml/apihelpers.pxi", line 1491, in lxml.etree._utf8
TypeError: Argument must be bytes or unicode, got 'list'
由于错误指出它应该是unicode,因此我添加了代码
values = base64.b64encode(values)
但是它给出了错误
Traceback (most recent call last):
File "./xml.py", line 10, in <module>
values = base64.b64encode(values)
File "/usr/lib/python2.7/base64.py", line 54, in b64encode
encoded = binascii.b2a_base64(s)[:-1]
TypeError: b2a_base64() argument 1 must be string or buffer, not list
我尝试这样做 ''' 值= [x.encode('utf-8')for x in values] '''
结果显示
<FileName>['1235362363151512d12d']</FileName>
这不是我期望的。我希望结果是
<FileName>1235362363151512d12d</FileName>
#!/usr/bin/python
from lxml import etree as ET
root = ET.Element("alphanumeric")
file = open("alphanumeric.txt", "r")
for aline in file:
values = aline.split()
length = len(values)
child = ET.SubElement(root,"child")
fn = ET.SubElement(child, "FileName")
fn.text = values
tree = ET.ElementTree(root)
tree.write("filename.xml")
x = ET.parse("filename.xml")
print ET.tostring(x, pretty_print=True)
alphanumeric.txt
7dc1f0e60f11c456aa15cc3546716c17
a78212faa38ef1078b300a492997fc02
7fa8c07634f937a1fcef9180531dc2e4
723fe720cb63189ddafde5045c4a7baf
6e670a837970a1fb4161d77d5f720d318d7e4dbc
4532b6f08b0d71893394e74e591a943bbc625f1c
3752656c024284ea63421d70235ec48d76a95df3
3f5505b9fad4cd5a1b934fee505942d28682ab91
5e7663f662cedcc2c520b88928824a4c7caf5a6833f77cdb0051328d74ace1c8
640ff11e6a0f8d95ac26e28ab6cefc29615795a646e40ce63c3ddc5f55bc165a
80b3e424c96bc9bdeafaac2a8fe2f21319663604b4b324d57c065a8a804a3a00
我希望结果是一个漂亮的XML。但是取而代之的是关于参数的错误,必须使用字节或unicode。该变量导致错误。将变量附加到xml的正确方法是什么?
答案 0 :(得分:2)
您的values = aline.split()
语句似乎是问题的根源。尝试以这种方式修改for
循环,看看它是否有效:
for aline in file:
child = ET.SubElement(root,"child")
fn = ET.SubElement(child, "FileName")
fn.text = aline
tree = ET.ElementTree(root)