简体   繁体   中英

Json File Handling in Python: Writing input to file

this is my code that Im trying to get to write into a JSON file in the format {"Example1": "Example"} Im getting an error which reads:

db_file.write(json.dump({"Admin": keyPass}, db_file)) TypeError: must be str, not None

For this code:

         keyPass = input("Create Admin Password » ")                    
         with codecs.open(os.path.join(PATH), 'w') as db_file:
             db_file.write(json.dump({"Admin": keyPass}, db_file))

This is the weird part, it creates it in the file fine and how I want it to be formatted is correct, yet it still comes up with the error above.

Could anyone please help me with what I need to correct here?

The first two arguments to the json.dump function are:

  • obj: The object to serialize
  • fp: A file-like object to write the data to

So what's happening here, is the inner call to json.dump is successfully writing the JSON-encoded string to your file, but then you're trying to pass the output of it (which will always be None) to your fileobject's write function.

You have two options:

  1. use json.dumps(stringToEncodeAsJSON) instead of json.dump, which will return the JSON formatted string which can then be written to your file using your fileObject's write function
  2. Remove the fileObject's write function from around the json.dump call

Update:

Here are some examples of how you could do it

keyPass = input("Create Admin Password > ")

with open(pathName, 'w') as db_file:
    db_file.write(json.dumps({"Admin": keyPass}))

with open(pathName, 'w') as db_file:
    json.dump({"Admin": keyPass}, db_file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM