2012-07-17 77 views
1

我從兩個XML文件中提取信息爲2個字典,因爲我想比較這些文件並更改其中一個文件中的信息。將Python字典的值寫回文件

這是我的字典:

源詞典:

d_source={'123': 'description_1', '456': 'description_2'} 

目標詞典:

d_target={'123': '\n', '456': 'description_2'} 

這是我的替換代碼:

for i in d_source: 
    for j in d_target: 
     if d_target[j]=='\n': 
      d_target[j]=d_source[i] 
print (d_target) 

d_target更新爲

d_target = {'123': 'description_1', '456': 'description_2'} 

但是,我從中提取字典的原始文件保持不變。我在這裏錯過了什麼?

+4

如果您修改字典,您如何期待Python代碼修改文件? – Blender 2012-07-17 07:52:51

+0

我不知道,這就是爲什麼我問....我是Python新手。我以爲我可以將字典重新導入到我的文件中,但不知道如何。 – Kaly 2012-07-17 07:55:21

+2

您需要將字典寫回文件,字典和文件之間沒有鏈接。 – 2012-07-17 08:03:23

回答

2

其中一個解決方案,爲您將是:

比方說,你想打印它作爲一個JSON,它,如果你已經使用類型的字典是有道理的。

import json 
output = json.dumps(d_target) 

f = open("myfile", 'w') 
f.write(output) 
f.close() 

這將打印您的字典作爲json文件myfile。

如果你想要它作爲一個XML你可以使用elementtree模塊。

那麼你可以使用這樣的事情:

from elementtree import ElementTree as ETree 
ET = ETree 
ET.xml_declaration = "true" 
products = ET.Element("products") 
properties = ET.Element("properties") 
products.append(properties) 
products.attrib["xmlns"] = "http://schema.example.com/product_data_1.0" 
update = ET.Element("update") 
delete = ET.Element("delete") 
products.append(delete) 
products.append(update) 

這僅僅是一個例子,看看它是如何做,這會造成類似:

<products xmlns="http://schema.example.com/product_data_1.0"> 
     <properties /> 
     <delete /> 
     <update /> 
</products> 

並打印此XML來再次提交文件:

output = ET.tostring(products, "utf-8") 
f = open("xml", 'w') 
f.write(output) 
f.close() 
+0

JSON很簡單。由於沒有一對一映射,XML通常會更難一些。但總的來說,這種方法是正確的。反序列化,更改,然後序列化。 – Krumelur 2012-07-17 08:26:35

+0

好主意!但不幸的是,我需要一個XML輸出,否則我無法將該文件重新導入到我的軟件中:/。 – Kaly 2012-07-17 08:39:33

0

您的替換代碼(在您的示例中)可以替換爲.update()方法dict

d_target.update(d_source) 

我不知道你想怎麼來持久dict但使用json模塊是一個選項。否則,如果您想要更新的XML文件,則必須查看修改節點中的屬性,並在「somelibraryhere」.tostring()的(或類似的)方法中寫入結果。