[英]Python writes empty json file
I'm working on a console app in python. 我正在使用python中的控制台应用程序。 I have a command that should save the program state as a json file, but when I write the file, it's empty.
我有一个命令应该将程序状态保存为json文件,但是当我写文件时,它是空的。 The result of .as_list() here is a list containing an arbitrary 3-lists.
这里.as_list()的结果是一个包含任意3个列表的列表。
class SaveCommand():
def __init__(self, console):
self.console = console
def execute(self, args):
if self.console.combat is None:
raise ConsoleCommandException("there is no active combat")
if len(args) != 1:
raise ConsoleCommandException("save [save name]")
try:
with open("save_files/" + args[0] + ".json", "w") as outfile:
json.dumps(self.console.combat.as_list(), outfile)
except Exception:
raise ConsoleCommandException("save failed: unknown error")
print("successfully saved \"" + args[0] + "\"")
json.dumps
doesn't write a file, it returns the string serialized as JSON. json.dumps
不写文件,它返回序列化为JSON的字符串。 You're looking for json.dump
. 你在找
json.dump
。 Notice the missing fp
param for dumps
. 注意
dumps
丢失的fp
参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.