2

recently i started learning Python and encountered a problem i can`t find an answer to. Idea of the program is to ask for username, load a dictionary from JSON file, and if the name is in the dictionary - print the users favourite number.

The code, that loads the JSON file looks like this:

import json

fav_numbers = {}
filename = 'numbers.JSON'

name = input('Hi, what`s your name? ')
try:
    with open(filename) as f_obj:
        fav_numbers = json.load(f_obj)
except FileNotFoundError:
    pass

if name in fav_numbers.keys():    

    print('Hi {}, your fav number is {}, right?'.format(name, fav_numbers[name]))

else:
    number = input('Hi {}, what`s your favourte number? '.format(name))
    fav_numbers[name] = number

    with open(filename, 'w') as f_obj:
        json.dump(fav_numbers, filename)

Still, as i try to run it, it crashes, telling me:

Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'numbers.JSON'
  File "/home/niedzwiedx/Dokumenty/Python/ulubionejson.py", line 22, in <module>
    with open(filename) as f_obj:

What i`m doing wrong to catch the exception? (Already tried changing the FileNotFoundError to OSError or IOError)

Ni3dzwi3dz
  • 177
  • 8
  • 3
    Cannot reproduce. Is this really all your code? – Mike Scotty Jan 23 '20 at 10:49
  • The error probably comes from somewhere else in your code. Can you provide more code and the full traceback for the error ? – Valentin M. Jan 23 '20 at 10:52
  • actually this is not enough information – aNup Jan 23 '20 at 11:00
  • Thanks for fast reply. I added full code and error message. – Ni3dzwi3dz Jan 23 '20 at 11:02
  • Your edited code should not match the error provided. If the file does not exists, it should fail on line 13 with a ``KeyError`` when accessing ``if fav_numbers[name]: `` As for your edited question: line 22 is not wrapped in a ``try..except`` block, only the lines 8 and 9 are. – Mike Scotty Jan 23 '20 at 11:12
  • Thanks. I edited it and it should work now. – Ni3dzwi3dz Jan 23 '20 at 11:17
  • Your traceback still does not match the code you provide : `with open(filename) as f_obj:` in you traceback is actually `with open(filename, 'w') as f_obj:` in your code. Are you sure that you run the same file that you are editing ? – Valentin M. Jan 23 '20 at 13:32

1 Answers1

2

The error comes from you last line, outside of your try/except

with open(filename, 'w') as f_obj:
        json.dump(fav_numbers, filename)

filename is a string, not a file.

You have to use

with open(filename, 'w') as f_obj:
        json.dump(fav_numbers, f_obj)

For additional safety, you can surround this part with try/except too

try:
    with open(filename, 'w') as f_obj:
        json.dump(fav_numbers, f_obj)
except (FileNotFoundError, PremissionError):
    print("Impossible to create JSON file to save data")

Valentin M.
  • 520
  • 5
  • 19