python打印到文件而不是输出屏幕
我有以下python脚本(它将xml“转换”为例如json): 当我运行以下代码时,它将输出json代码。问题是;如何将输出写入output.json,而不是将输出写入屏幕python打印到文件而不是输出屏幕,python,json,xml,Python,Json,Xml,我有以下python脚本(它将xml“转换”为例如json): 当我运行以下代码时,它将输出json代码。问题是;如何将输出写入output.json,而不是将输出写入屏幕 谢谢 将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
谢谢 将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)
将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)
要使用缩进格式化json,可以使用缩进参数()
要使用缩进格式化json,可以使用缩进参数()
要将字典
dct
写入文件,请使用
要从文件中读取词典,请使用
结合两个例子
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'}
要将字典
dct
写入文件,请使用
要从文件中读取词典,请使用
结合两个例子
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'}
为什么不使用
json.dump()
直接写入文件?@quamrana,我认为file.write(json.dumps(data))
和json.dumps(data,file)
之间没有任何区别。第一个变量对我来说更“明显”。为什么不使用json.dump()
直接写入文件?@quamrana,我认为file.write(json.dumps(data))
和json.dumps(data,file)
之间没有任何区别。第一种变体对我来说更“明显”。Hi@HRR1337请检查下面我的答案,看它是否对你有帮助:)Hi@HRR1337请检查下面我的答案,看它是否对你有帮助:)
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'}