简体   繁体   中英

Python: json.load cannot read data from a file

I am trying to write a simple code which stores username in json file. 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:

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 ? I expect message "Welcome back, test"

After the first json.load ie,

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

the file pointer is at the end of the file . So when you press '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) ).

So you should seek to the first position of the file and read it again.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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