I can’t run my python file due to error saying
File "Application.py", line 32, in __init__
self.json_file = open("Models\model_new.json", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'Models\\model_new.json'
This is my program code
class Application:
def __init__(self):
self.hs = Hunspell('en_US')
self.vs = cv2.VideoCapture(0)
self.current_image = None
self.current_image2 = None
self.json_file = open("Models\model_new.json", "r")
self.model_json = self.json_file.read()
self.json_file.close()
self.loaded_model = model_from_json(self.model_json)
self.loaded_model.load_weights("Models\model_new.h5")
I’m using Ubuntu 22.04 LTS, and this is my
path folder
>Solution :
In Linux, your directories are separated by a forward slash. So your path would be: Models/model_new.json.
To make your python-scripts work on different operating systems, you can use the os-module:
import os
path = os.path.join("Models", "model_new.json")
self.json_file = open(path, "r")
If you’re interested, where the second slash comes from: This happens, because \ is used as a special character in strings to represent e.g. newline \n or a tab \t among others. I don’t think, that there is one for \m, so python still sees it as just a backslash, but to play it save python does escape the backslash using another one \\. This is then the safe representation of a backslash in a string.
You can view this, when printing the repr of your string:
print(repr("Models\model_new.json"))
>>> 'Models\\model_new.json'