简体   繁体   English

Python:json.load无法从文件读取数据

[英]Python: json.load cannot read data from a file

I am trying to write a simple code which stores username in json file. 我正在尝试编写一个将用户名存储在json文件中的简单代码。 If file already exists - additional question (simple verification) will appear. 如果文件已经存在-将会出现其他问题(简单验证)。

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!')

When I press Y, Python crashes with the following errors: 当我按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)

Please explain - why json.load not working when I press Y ? 请解释-为什么当我按Y时json.load无法正常工作? I expect message "Welcome back, test" 我希望收到消息“欢迎回来,测试”

After the first json.load ie, 在第一个json.load之后,即

print('Are you ' + json.load(file) + '?')

the file pointer is at the end of the file . 文件指针位于file So when you press 'Y' 所以当你按'Y'

if check_username == 'Y':
      print('Welcome back, ' + json.load(file))

there are no more items left to read from its current position( json.load(file) ). 从当前位置( json.load(file)json.load(file)需要读取其他项目。

So you should seek to the first position of the file and read it again. 因此,您应该seek文件的第一个位置并再次阅读。

if check_username == 'Y':
      file.seek(0)
      print('Welcome back, ' + json.load(file))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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