![](/img/trans.png)
[英]Python - get column iterator from a file (without reading the whole file)
[英]How to overwrite an XML attribute value without reading the whole file in python
一次只讀取一個元素時,如何覆蓋單個屬性值?
具體來說,我正在使用xml.etree.cElementTree.iterparse()
讀取每個單獨的元素。 然后,我要更改屬性值。
然后,我要做的就是用changed element
覆蓋original element
changed element
。
這是到目前為止的示例代碼:
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的注釋中解釋了為什么這是不可能的。
那可能行不通。 XML處理不知道數據來自文件,因此無法在文件中完全相同的位置“回寫”更改后的值。 即使可以:在沒有重寫整個文件的情況下,用較短或較長的文本替換文件中的文本在物理上也是不可能的。 (唯一的例外是“長度完全相同的文本”和“數據在最后”。)– usr2564301
iterparse仍會處理整個樹。 您無法避免:
http://effbot.org/zone/element-iterparse.htm#incremental-parsing
增量解析#請注意,iterparse仍然像解析一樣構建一棵樹,但是您可以在解析時安全地重新排列或刪除樹的某些部分。 例如,要解析大型文件,您可以在處理完元素后立即刪除它們:
對於事件,iterparse(source)中的elem:如果elem.tag ==“ record”:...處理記錄元素... elem.clear()
如果您的XML文件太大而無法在程序中處理,則需要考慮另一種數據存儲格式,例如數據庫。
否則,您可以使用sed和awk或其他工具對文本文件進行一些文件操作魔術。
我最近也一直在處理大型文件,但無法將其容納在內存中。 為了解決這個問題,我整理了一個簡單的軟件包bigread
( pip install bigread
),該軟件包將文件的n行立即流進RAM:
from bigread import Reader
# this will be the output file
with open('updated.xml', 'w') as out:
# read the input file
for i in Reader(file='input.xml', block_size=1):
# check if this is a line you need to operate on
if i.lstrip()[:5] == '<tag ':
# replace the target attribute
i = i.replace(' attr="cats" ', ' attr="dogs" ')
# write the new line to disk
out.write(i + '\n')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.