Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python writes empty json file

Tags:

python

json

I'm working on a console app in python. I have a command that should save the program state as a json file, but when I write the file, it's empty. The result of .as_list() here is a list containing an arbitrary 3-lists.

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] + "\"")
like image 455
icaughtfireonce Avatar asked Apr 27 '16 22:04

icaughtfireonce


1 Answers

json.dumps doesn't write a file, it returns the string serialized as JSON. You're looking for json.dump. Notice the missing fp param for dumps.

like image 194
TankorSmash Avatar answered Oct 12 '22 23:10

TankorSmash