Reputation: 1
import json
filename = 'username.json'
try:
with open(filename) as fo:
username = json.loads(fo)
except FileNotFoundError:
user = input("Tell me your username? ")
print("I'll remember you next time! " + user + " !")
with open(filename ,'w') as fo:
json.dump(user ,fo)
else:
print("So we meet again " +userame +" !")
output:
PS C:\Users\gagan\Desktop\python crash course> python jsonfile.pyTraceback (most recent call last):
File "jsonfile.py", line 5, in <module>
username = json.loads(str(fo))
File "C:\Users\gagan\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\gagan\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\gagan\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Upvotes: 0
Views: 189
Reputation: 4680
You're passing the file handle to json.loads
, which expects a string. Instead you either want to use json.load
(no 's'):
username = json.load(fo)
Or use json.loads
(with the 's' at the end, which stands for 'string') with the file contents:
username = json.loads(fo.read())
Upvotes: 2