You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 22:22:19