当您一次只读取一个元素时,如何覆盖单个属性值?
具体来说,我使用 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/