2015-10-23 27 views
1

後,我有這樣的代碼:蟒蛇:如何物理保存XML文件更改

country.xml:

<country name="Liechtenstein"> 
<rank>1</rank> 
<year>2008</year> 
<gdppc>141100</gdppc> 
<neighbor direction="E" name="Austria"/> 
<neighbor direction="W" name="Switzerland"/> 

和:

from xml.dom import minidom 
xmldoc = minidom.parse('country.xml') 
print(xmldoc.toxml()) 
country = xmldoc.getElementsByTagName("country") 
firstchild = country[0] 
print(firstchild.attributes["name"].value) 
firstchild.attributes["name"].value = "Germany" 
print(xmldoc.toxml()) 

文檔有將國家名稱從: 「列支敦士登」 TO 「Germany」

我的問題是如何將更改保存回country.xml文件? 謝謝

回答

1

您可以簡單地打開該文件,並將xmldoc.toxml()的輸出寫入它。示例 -

... 
with open('country.xml','w') as f: 
    f.write(xmldoc.toxml()) 
+0

非常感謝,它的工作原理。 –