0

我是 python 新手,我收到以下错误。

$ python testrun.py 
Traceback (most recent call last):
  File "testrun.py", line 13, in <module>
    with open(tree, 'w') as file_handle:
TypeError: coercing to Unicode: need string or buffer, lxml.etree._ElementTree found

使用此代码:

from lxml import etree
tree = etree.parse('testregression_config.xml')

for elem in tree.findall('.//xmpp'):
    #assert elem.attrib['name'] == 'test02'
    elem.attrib['name'] == 'test03'

for elem in tree.findall('.//xmpp-config'):
    #assert elem.text == 'QA'
    elem.text = 'Prod'

with open(tree, 'w') as file_handle:
    file_handle.write(etree.tostring(tree, pretty_print=True, encoding='utf8'))

<config>
  <logging/>
  <test-mode>false</test-mode>
  <test name="test02">
    <mail/>
    <test-system>0</test-system>
    <system id="0" name="suite1" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="1" name="suite2" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="2" name="suite3" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="3" name="suite4" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="4" name="suite5" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
  </test>
</config>
4

1 回答 1

2

在这一行

with open(tree, 'w') as file_handle:

您将 lxml.etree._ElementTree 对象作为文件名传递。您可能错过了报价并打算

with open('tree', 'w') as file_handle:

错误消息和回溯是不言自明的

错误位置with open(tree, 'w') as file_handle:所以它与open语句有关

错误信息TypeError: coercing to Unicode: need string or buffer, lxml.etree._ElementTree found

所以看起来我们正在传递lxml.etree._ElementTree而不是一个字符串到open. 当然,我们正在这样做,我们传递tree的不是字符串,而是tree = etree.parse('testregression_config.xml'),根据您文件中的第二条语句

于 2013-01-29T15:27:04.603 回答