【问题标题】:python print to file instead output screenpython打印到文件而不是输出屏幕
【发布时间】:2019-05-09 07:38:43
【问题描述】:

我有以下 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 而不是输出到屏幕?

谢谢!

【问题讨论】:

  • 嗨@HRR1337,请检查我的回答,看看它是否对你有帮助:)

标签: python json xml


【解决方案1】:

要使用缩进格式化 json,您可以使用 indent 参数 (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

【讨论】:

  • 为什么不用json.dump()直接写入文件呢?
  • @quamrana,我认为file.write(json.dumps(data))json.dumps(data, file) 之间没有任何区别。第一个变体对我来说更“明显”。
【解决方案2】:

将 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)

【讨论】:

    【解决方案3】:

    要将您的字典 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'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      • 2019-06-26
      • 2022-01-07
      相关资源
      最近更新 更多