【问题标题】:FileNotFoundError in "Python Crash Course"“Python 速成课程”中的 FileNotFoundError
【发布时间】:2022-01-02 16:33:26
【问题描述】:

我一直在使用“Python Crash Course”这本书来学习 Python。我目前在第 233-234 页,似乎无法让程序运行。我应该导入船的图像,但每次我尝试使用行 self.image = pygame.image.load("images/Ship.bmp") 执行此操作时,我都会收到一条错误消息“FileNotFoundError:在工作目录中找不到文件'Ship.bmp'。我的工作在哪里目录以及如何在那里获取我的文件?(使用视觉学习)

class Ship:

    def __init__(self, ai_game):
        self.screen = ai_game.screen
        self.screen_Rect = ai_game.screen.get_rect()

        self.image = pygame.image.load("images/Ship.bmp")
        self.rect = self.image.get_rect()

        self.rect.midbottom = self.screen_rect.midbottom

    def blitme(self):
        self.screen.blit(self.image, self.rect)

在不同的类别中:

    self.ship = Ship(self)

【问题讨论】:

  • 当前工作目录 (CWD) 是一个操作系统概念,始终存在一个,但它可能不是您的 .py 文件所在的位置。解决这种情况的最佳方法是从.py 文件的路径中提取目录,该文件 存储在预定义的__file__ 变量中,然后使用os.path.join() 创建完整路径图像文件——不管当前工作目录是什么,它都可以工作。
  • 我编辑了需要的其余部分
  • 仅供参考,这是current working directory 上的维基百科文章。操作系统将一个与每个进程关联起来。

标签: python visual-studio visual-studio-code


【解决方案1】:

以下是如何根据脚本文件的位置确定图像文件的绝对路径。无论当前工作目录是什么,这样做都会使您的代码正常工作。

它使用pathlib 模块中的Path 类使事情变得非常简单(没有必要使用os.path 来做我在comment 中提到的事情——尽管它也可以使用它来完成)。

from pathlib import Path

class Ship:
    # Determine absolute path from relative path.
    image_path = Path(__file__).parent / "images/Ship.bmp"

    def __init__(self, ai_game):
        self.screen = ai_game.screen
        self.screen_Rect = ai_game.screen.get_rect()

        self.image = pygame.image.load(self.image_path)
        self.rect = self.image.get_rect()

        self.rect.midbottom = self.screen_rect.midbottom

    def blitme(self):
        self.screen.blit(self.image, self.rect)

print(Ship.image_path)  # -> Will show absolute path to image file.

我不确定您所说的“在不同的类中:”部分是什么意思(甚至下面显示的代码的 sn-p 应该完成什么)。

【讨论】:

  • 那行得通。谢谢!
猜你喜欢
  • 2021-08-28
  • 1970-01-01
  • 2011-09-08
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-20
  • 1970-01-01
相关资源
最近更新 更多