I tried running this code and get error:
Traceback (most recent call last):
File "/Users/ccharest/Desktop/PCC/remember_me_2.py", line 7, in <module>
username = json.load(f_obj)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 268, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
What is wrong with this block of code?
import json
filename = 'username2.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name? ")
username = username.title()
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back {}!".format(username))
else:
print("Welcome back {}!".format(username))
UPDATE 1 As suggested by some, I changed the filename from "usernam2.json" to "uname.json" and it worked... Why would using filename "username2.json" trigger the error???
UPDATE 2 As suggested by Alexander Huszagh, the file "username2.json" was created, but was empty.I deleted the file "username2.json" and ran the script again and it worked fine.
username2.jsonis not valid.username2.jsonmight not be valid JSON. Can you post the contents of the file?