用于创建XML文件的Python脚本适用于Python 2.7.3,但不适用于Python 2.7.9

时间:2016-08-18 19:46:00

标签: xml python-2.7

前段时间我在Raspberry PI 2上编写了一个Python脚本,现在我正在尝试将脚本移动到新的PI 3.脚本在RPI3上生成错误。我可以在RPI之间看到的唯一区别是新的有Python 2.7.9,而RPI2有python 2.7.3!

以下代码适用于一个而不是另一个(注意我在脚本中删除了很多其他代码以解决基本问题)。

import lxml.etree as ET

currenttemp = 28
root = ET.Element("root")
today_current = ET.SubElement(root, "today_current")
ET.SubElement(today_current, "currenttemp").text = str(currenttemp)
tree = ET.ElementTree(root)
tree.write("templates/weather.xml", method="xml", pretty_print=True)

最后一行产生以下错误:

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    tree.write("templates/weather.xml", method="xml", pretty_print=True)
  File "lxml.etree.pyx", line 1938, in lxml.etree._ElementTree.write (src/lxml/lxml.etree.c:57624)
  File "serializer.pxi", line 479, in lxml.etree._tofilelike (src/lxml/lxml.etree.c:122901)
  File "serializer.pxi", line 525, in lxml.etree._create_output_buffer (src/lxml/lxml.etree.c:123405)
  File "serializer.pxi", line 514, in lxml.etree._create_output_buffer (src/lxml/lxml.etree.c:123246)
IOError: [Errno 2] No such file or directory

有关此错误发生原因的任何想法?

1 个答案:

答案 0 :(得分:0)

请在旧机器和新机器上运行此操作以确定这是否是编写templates/weather.xml的问题:

#!/usr/bin/env python                                                                                                                                                                                     
import os
print('this is the current directory: {}'.format(os.getcwd()))
print('here are the directory contents:')
for item in os.listdir('.'):
    print(item)