将Python字典的值写回文件 [英] Write values of Python dictionary back to file
问题描述
我将信息从两个XML文件中提取到2个字典中,因为我想比较这些文件并在其中一个更改信息。
这些是我的字典: p>
源字典:
d_source = {'123':'description_1' ,'456':'description_2'}
目标字典:
d_target = {'123':'\\\
','456':'description_2'}
这是我的替换代码:
for d in d_source:
d_target中的j
如果d_target [j] =='\\\
':
d_target [j] = d_source [i]
print(d_target)
d_target更新为
d_target = {'123':'description_1','456':'description_2'}
然而,我提取字典的原始文件保持不变。我在这里缺少什么?
您的解决方案之一是:
假设您要将其打印为json,如果您已经在使用dict,这是有道理的。
import json
output = json.dumps(d_target)
f = open(myfile,'w')
f.write(输出)
f.close ()
这将打印您的dict将文件作为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删除)
products.append(update)
这只是一个例子来看看它这样做会产生一些类似的东西:
< products xmlns =http://schema.example.com/product_data_1 0.0\" >
< properties />
< delete />
< update />
< / products>
并再次将此xml打印到文件中:
$ $
f = open(xml,'w')
f.write(output )
f.close()
I extracted information from two XML files into 2 dictionaries because I wanted to compare these files and change information in one of them.
These are my dictionaries:
source dictionary:
d_source={'123': 'description_1', '456': 'description_2'}
target dictionary:
d_target={'123': '\n', '456': 'description_2'}
This is my replacement code:
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 is updated to
d_target = {'123': 'description_1', '456': 'description_2'}
However, my original files from which I extracted the dictionaries remain unchanged. What am I missing here?
One of the solutions for you would be:
Let's say you want to print it as a json, it makes sense if you are already using dicts.
import json
output = json.dumps(d_target)
f = open("myfile", 'w')
f.write(output)
f.close()
This will print your dict to file myfile as a json.
And if you want it as a xml you can use elementtree module.
Then you could use something like this:
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)
This is just an example to see how it is done and this would create something like:
<products xmlns="http://schema.example.com/product_data_1.0">
<properties />
<delete />
<update />
</products>
And to print this xml to file again:
output = ET.tostring(products, "utf-8")
f = open("xml", 'w')
f.write(output)
f.close()
这篇关于将Python字典的值写回文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!