Ubuntu 22.04 LTS下Python运行报错:No such file or directory
问题解决:FileNotFoundError 找不到文件或目录
问题原因
Ubuntu属于Linux系统,路径分隔符使用正斜杠(/),但你代码里用了Windows系统的反斜杠()。同时反斜杠在Python字符串中是转义字符,实际传递的路径会变成Models\\model_new.json,和实际目录结构不匹配,导致文件找不到。
解决方案
方案1:直接替换路径分隔符
把代码中的反斜杠改成正斜杠即可:
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")
方案2:使用跨平台路径拼接(推荐)
用Python内置的os.path模块拼接路径,自动适配不同系统的分隔符:
import os class Application: def __init__(self): self.hs = Hunspell('en_US') self.vs = cv2.VideoCapture(0) self.current_image = None self.current_image2 = None # 跨平台拼接路径 json_path = os.path.join("Models", "model_new.json") self.json_file = open(json_path, "r") self.model_json = self.json_file.read() self.json_file.close() self.loaded_model = model_from_json(self.model_json) # 权重文件路径同理 weights_path = os.path.join("Models", "model_new.h5") self.loaded_model.load_weights(weights_path)
注意:确认Models文件夹和Application.py处于同一目录下(从你的文件夹结构来看符合该条件)。
内容的提问来源于stack exchange,提问作者Jaygee
相关产品推荐
相关产品推荐

