I can’t run my python file due to error saying
File "Application.py", line 32, in __init__
self.json_file = open("Modelsmodel_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("Modelsmodel_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("Modelsmodel_new.h5")
I’m using Ubuntu 22.04 LTS, and this is my
path folder
2
Answers
You need to make sure you’re running your script in the directory you intend to. You can check this by running
os.getcwd()
orPath.cwd()
to see where the interpreter currently is.Secondly, since you’re on Ubuntu, you’re going to have to change the backslash to a forwardslash, so that your path will be:
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:
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 tabt
among others. I don’t think, that there is one form
, 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: