Ubuntu下VS Code文件路径访问报错:FileNotFoundError问题求助
解决文件路径找不到问题(FileNotFoundError)
问题描述
跟着YouTube教程在VS Code中制作国际象棋游戏时,出现报错:
FileNotFoundError: No such file or directory: '/home/phalit/Documents/PYTHON/CHESS-AI/src/images/imgs=80px/black_rook.png'
此前也曾遇到路径访问文件的问题,需要解决。
相关代码
import os class Piece: def __init__(self,name,color,value,texture=None,texture_rect=None): self.name = name self.color = color if color=='white': value_sign = 1 else: value_sign = -1 self.value = value*value_sign self.texture = texture self.set_texture() self.texture_rect = texture_rect def set_texture(self,size=80): self.texture=os.path.join( f'/home/phalit/Documents/PYTHON/CHESS-AI/src/images/imgs={size}px/{self.color}_{self.name}.png') def add_moves(self,move): self.moves.append(move) class Pawn(Piece): def __init__(self,color): if color == 'white': self.dir = -1 else: self.dir = +1 super().__init__('pawn',color,1,0) class Knight(Piece): def init(self,color): super().init('knight',color,3.0) class Bishop(Piece): def init(self,color): super().init('bishop',color,3.001) class Rook(Piece): def init(self,color): super().init('rook',color,5.0) class Queen(Piece): def init(self,color): super().init('queen',color,9.0) class King(Piece): def init(self,color): super().init('king',color,10000.0)
解决步骤
- 验证文件路径真实性
手动检查/home/phalit/Documents/PYTHON/CHESS-AI/src/images/imgs=80px/目录下是否存在black_rook.png文件。Linux系统路径区分大小写,需确认文件名、路径拼写完全匹配。 - 改用相对路径替代绝对路径
绝对路径易因环境变化出错,修改set_texture方法使用相对路径:def set_texture(self,size=80): # 获取当前脚本所在目录 current_dir = os.path.dirname(os.path.abspath(__file__)) # 按实际目录结构调整层级 self.texture = os.path.join( current_dir, f'../images/imgs={size}px/{self.color}_{self.name}.png' ) - 核对项目目录结构
确认目录结构是否符合预期,示例结构如下:
若结构不符,调整路径中的目录层级。CHESS-AI/ ├── src/ │ ├── 你的脚本文件.py ├── images/ │ ├── imgs=80px/ │ ├── black_rook.png │ ├── 其他棋子图片... - 修复子类构造方法错误
注意到Knight、Bishop等子类的构造方法写错为init,需改为__init__,修正后示例:class Knight(Piece): def __init__(self,color): super().__init__('knight',color,3.0) class Bishop(Piece): def __init__(self,color): super().__init__('bishop',color,3.001)
内容的提问来源于stack exchange,提问作者habibigaju
相关产品推荐
相关产品推荐

