[英]Python: json.load cannot read data from a file
我正在嘗試編寫一個將用戶名存儲在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無法正常工作? 我希望收到消息“歡迎回來,測試”
在第一個json.load
之后,即
print('Are you ' + json.load(file) + '?')
文件指針位於file
。 所以當你按'Y'
if check_username == 'Y':
print('Welcome back, ' + json.load(file))
從當前位置( json.load(file)
) json.load(file)
需要讀取其他項目。
因此,您應該seek
文件的第一個位置並再次閱讀。
if check_username == 'Y':
file.seek(0)
print('Welcome back, ' + json.load(file))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.