python - 如何在 python 中覆盖 XML 属性值而不读取整个文件

标签 python xml xml.etree

当您一次只读取一个元素时,如何覆盖单个属性值?

具体来说,我使用 xml.etree.cElementTree.iterparse() 来读取每个单独的元素。然后我正在更改属性值。

然后我需要做的是用更改的元素覆盖原始元素

这是到目前为止的示例代码:

osm_file = open(sample.osm, 'r+')

for event, elem in ET.iterparse(osm_file events=("start",)):

    # Making some changes
    elem.attrib['v'] = 'new_value'

    # Some how write the elem back to the XML file

我不能做的一件事是将整个 XML 文件读入 python,因为该文件太大。

最佳答案

评论中发布的 usr2564301 解释了为什么这是不可能的。

That cannot possibly work. The XML handling is unaware that the data came from a file and so it cannot "write back" the changed value at the exact same position in the file. Even if it could: it is physically impossible to replace a text in a file with a shorter or longer text without rewriting the entire file. (The very only exceptions being "exactly the same length text" and "the data is at the very end".) – usr2564301

关于python - 如何在 python 中覆盖 XML 属性值而不读取整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51091217/

相关文章:

python - AttributeError: 'tuple' 对象没有属性 'write'

android - 在 Eclipse 中自动生成 xml 布局的 java 代码

android, sax解析器重复错误

xml - 在 Sublime Text 2 中打开时如何自动缩进 XML 文件?

python - 使用 etree 从文件中解析 xml 在读取字符串时有效,但在读取文件时则无效

python - 如何使用 QName(python xml.etree.ElementTree?)

python - 如何修复 'BlobService' 未定义'错误

python - 双对数图中的 Matplotlib 箭头

python-3.x - XML 到 CSV Python

Python3 (v3.2.2) 写入二进制文件时的额外位