在python中将xml作为txt读取

时间:2015-04-20 18:30:05

标签: python xml

我在python中有以下代码(仅从txt加载数据):

def main():
    f = open("text.txt", "r" ) //load txt
    a = [] // new array
    for line in f:
        a.append(line.strip()) //append line

main()

如何使用xml file? f = open("myxml.xml", "r" )无法正常工作。我收到错误:UnicodeDecodeError: 'charmap' codec can't decode byte 0x88 in position 4877: character maps to <undefined>

2 个答案:

答案 0 :(得分:1)

这与xml文件格式无关,但与您的文件encoding无关。 Python3假定所有内容都在utf-8,但如果你在Windows上,你的文件可能在windows-1252。你应该使用:

f = open("text.txt", "r", encoding="cp1252")

答案 1 :(得分:0)

这肯定能帮到你。

a=[]
with open('reboot.xml', 'r') as f:
    a = f.read()
f.closed
print a