编写Python字典的值返回到文件(Write values of Python dictionar

2019-07-30 11:03发布

我提取的信息来自两个XML文件转换成2个字典,因为我想比较这些文件,并在其中的一个改变的信息。

这是我的字典:

来源词典:

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'}

但是,我从我中提取的字典原始文件保持不变。 我缺少的是在这里吗?

Answer 1:

一个对你将是解决方案:

比方说,你想打印它作为一个JSON,它,如果你已经使用类型的字典是有道理的。

import json 
output = json.dumps(d_target)

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

这将打印您的字典,以myfile文件为JSON。

如果你想把它当作一个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()


Answer 2:

您所更换的代码(在你的例子)可以通过更换.update()上的一个方法dict

d_target.update(d_source)

我不知道你想怎么来持久dict ,但使用json模块是一个选项。 否则,如果你想更新的XML文件,你必须看看在节点修改属性,和写作的“somelibraryhere”的ToString()的(或类似)方法的结果。



文章来源: Write values of Python dictionary back to file