0

我正在尝试更改 xml 文档中的许多值。我尝试了一些不同的东西,但它们似乎没有改变任何东西,但随着修改时间的变化,它们似乎确实可以访问文件,但值没有。

from xml.etree import ElementTree as et
import os
import xml

path = os.path.expanduser(r'~\AppData\Roaming\etc\etc\somefile.xml')
et = et.parse(path)

for name in et.findall('name'):
    if name == 'sometext1':
        name.text = "sometext2"
et.write(path)

其次尝试了这个,但我得到了一个 AttributeError: 'str' object has no attribute 'text'

with open(path,'r+') as f:
tree = et.parse(f)

for node in tree.iter('favourite'):
name = node.attrib.get('name')

if name == 'sometext1':
    name.text = "sometext2"
tree.write(path)

谁能告诉我哪里出错了

4

1 回答 1

0
  • 线

    et = et.parse(path)
    

    右侧用作et模块,左侧用作变量名。在此之后,就不可能(或至少过于困难)访问 ElementTree 模块。如此消歧义et。比如说, ET成为模块,tree成为ElementTree.

  • 在 for 循环中,name是一个元素,因此与name字符串的比较总是 False。而是使用

    name.text == 'sometext1'
    

from xml.etree import ElementTree as ET
import os

path = os.path.expanduser(r'~\AppData\Roaming\etc\etc\somefile.xml')
tree = ET.parse(path)

for name in tree.findall('name'):
    if name.text == 'sometext1':
        name.text = "sometext2"
        print(name) # for debugging only
tree.write(path)
于 2013-05-12T23:58:33.397 回答