Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

No such file or directory

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading