我正在尝试编写一个将用户名存储在json文件中的简单代码。如果文件已存在-将会出现其他问题(简单验证)。
import json
username_file = 'username.json'
try:
with open(username_file) as file:
print('Are you ' + json.load(file) + '?')
check_username = input('Press Y if yes or N if no: ')
if check_username == 'Y':
print('Welcome back, ' + json.load(file))
if check_username == 'N':
username = input('Input your name: ')
with open(username_file, 'w') as file:
json.dump(username, file)
print('See you next time!')
except FileNotFoundError:
username = input('Input your name: ')
with open(username_file, 'w') as file:
json.dump(username, file)
print('See you next time!')
当我按Y时,Python崩溃并出现以下错误:
Are you test?
Press Y if yes or N if no: Y
Traceback (most recent call last):
File "C:/Users/medvedev_dd/PycharmProjects/untitled/test.py", line 9, in <module>
print('Welcome back, ' + json.load(file))
File "C:\Soft\Python\lib\json\__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Soft\Python\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Soft\Python\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Soft\Python\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)
请解释-为什么当我按Y时json.load无法正常工作?我希望收到消息“欢迎回来,测试”
答案 0 :(得分:0)
在第一个json.load
之后,即
print('Are you ' + json.load(file) + '?')
文件指针位于file
的末尾。因此,当您按'Y'
if check_username == 'Y':
print('Welcome back, ' + json.load(file))
从其当前位置(json.load(file)
)起没有其他项目可供读取。
因此,您应该seek
到文件的第一位置并再次读取。
if check_username == 'Y':
file.seek(0)
print('Welcome back, ' + json.load(file))