Ni3dzwi3dz
Ni3dzwi3dz

Reputation: 187

Python: FileNotFoundError not caught by try-except block

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)

Upvotes: 2

Views: 3425

Answers (1)

Valentin M.
Valentin M.

Reputation: 520

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")

Upvotes: 2

Related Questions