for some reason this code does not work, I don’t understand .. should work

import json numbers = [1 ,2 ,3 ,4 ,5 ,6 ,7] file_name = 'numbers.json' with open(file_name, 'w') as f_obj: json.dump(numbers, f_obj) 

The idea is to create a file - numbers.json, but it is not created. why I do not understand ...

then there should be such a code reading import json data

 file_name = 'numbers.json' with open(file_name) as f_obj: numbers = json.load(f_obg) print(numbers) 

but there is nothing because there is no file - can you give a hint?

  • what does not mean created? Have you tried to specify the full path to the file? - MaxU
  • so I have to create it before this? I thought it would create itself in this line - with open (file_name, 'w'). After all, python itself creates a file if it does not have this command? or don't I understand something? :) - Ruslan Rytchenko
  • no, specify the path to the file, for example: file_name = r'c:/temp/numbers.json' And correct: json.load(f_obg) -> json.load(f_obj) - MaxU
  • I understood thank you very much - Ruslan Rytchenko
  • if you correct the typo in the code, it works. What kind of error do you get? Are you sure this is FileNotFoundError (file not found), not NameError: name 'f_obg' is not defined (just a typo). The file is created in the current working directory (may differ from the folder with your script) The current directory in Python is jfs

1 answer 1

To be sure that the file being created will be written to the correct directory, you must either explicitly specify the full path to the file or change the current directory first.

 file_name = r'c:/temp/numbers.json' with open(file_name, 'w') as f_obj: json.dump(numbers, f_obj) 

or

 import os ... os.chdir(r'c:/temp') file_name = 'numbers.json' with open(file_name, 'w') as f_obj: json.dump(numbers, f_obj)