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です。そしてもちろん、私たちはそれをやっています、あなたのファイルの2番目のステートメントのようにtree、文字列ではなく、を渡しますtree = etree.parse('testregression_config.xml')

于 2013-01-29T15:27:04.603 に答える