Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 更改xml文件中的值_Python_Xml_Xml.etree - Fatal编程技术网

Python 更改xml文件中的值

Python 更改xml文件中的值,python,xml,xml.etree,Python,Xml,Xml.etree,我试图更改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('n

我试图更改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'对象没有属性'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)
有人能告诉我哪里出了问题吗
  • 线路

    et = et.parse(path)
    
    et
    用作右侧的模块和右侧的变量名 左边在这一点之后,这是不可能的(或者至少是太难了) 访问ElementTree模块。因此,消除et的歧义。比方说,,
    ET
    是模块,
    tree
    ElementTree

  • 在for循环中,
    name
    是一个元素,因此将
    name
    与 字符串将始终为False。改用

    name.text == 'sometext1'
    


  • name
    是元素的名称
    node
    是元素。我尝试了这些更改,但xml文件仍然没有发生任何更改。您确定
    tree.findall('name')
    正在查找元素吗?尝试在循环中放入
    print
    语句,以便查看是否找到元素。(可能找不到
    元素的一个原因是,您可能需要在中引用它。)
    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)