python打印到文件而不是输出屏幕

时间:2019-05-09 07:38:44

标签: python json xml

我有以下python脚本(它将xml“转换”为例如json):

import xmltodict
import pprint
import json

with open('file.xml') as fd:
    doc = xmltodict.parse(fd.read())

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(json.dumps(doc))

当我运行以下代码时,它将输出json代码。问题是;如何将输出写到output.json而不是输出到屏幕?

谢谢!

3 个答案:

答案 0 :(得分:1)

要将Json打印到文件中

with open("your_output_file.json", "w+") as f:
    f.write(json.dumps(doc))

要从文件读取JSON

with open("your_output_file.json") as f:
    d = json.load(f)

答案 1 :(得分:1)

要使用缩进格式设置json,可以使用缩进参数(link to docs)。

with open('file.xml', 'r') as src_file, open('file.json', 'w+') as dst_file:
    doc = xmltodict.parse(src_file.read()) #read file
    dst_file.write(json.dumps(doc, indent=4)) #write file

答案 2 :(得分:0)

要将字典dct写入文件,请使用json.dump

with open("output.json", "w+") as f:
    json.dump(dct,f)

要从文件中读取字典,请使用json.load

with open("output.json", "w+") as f:
    dct = json.load(f)

结合两个示例

In [8]: import json                                                                                                                                                               

In [9]: dct = {'a':'b','c':'d'}                                                                                                                                                   

In [10]: with open("output.json", "w") as f: 
    ...:     json.dump(dct,f) 
    ...:                                                                                                                                                                          

In [11]: with open("output.json", "r") as f: 
    ...:     print(json.load(f)) 
    ...:      
    ...:                                                                                                                                                                          
{'a': 'b', 'c': 'd'}