无法打开资源文件,pygame 错误:“FileNotFoundError:没有这样的文件或目录。”

Posted

技术标签:

【中文标题】无法打开资源文件,pygame 错误:“FileNotFoundError:没有这样的文件或目录。”【英文标题】:Could not open resource file, pygame error: "FileNotFoundError: No such file or directory." 【发布时间】:2020-01-30 07:04:07 【问题描述】:
Import pygame

pygame.init()

BG = pygame.image.load('_pycache_/test_bg.jpg')

def DrawGameWin():
    window.blit(BG,(0,0))

pygame.display.update()


DrawGameWin()

【问题讨论】:

错误信息听起来像是在硬盘上找不到文件。请检查您当前的工作目录以及您要打开的文件的路径! 它们都在我桌面上的一个文件夹中。我不确定下一步该做什么。我应该把我想上传的图片移到哪里。 Here 你可以看到如何检查你当前的工作目录。请检查您的假设是否正确。或者,您现在也可以提供完整路径,但这会破坏可移植性,因此请将此作为最后一个选项。 也许我不明白。我运行程序显示了路径。我将两者放在桌面上的同一个文件夹中。那不是同一条路吗?这不应该解决问题吗? 运行路径(即当前工作目录)很重要,而不是文件所在的文件夹。 【参考方案1】:

资源(图像、字体、声音等)文件路径必须相对于当前工作目录。工作目录可能与 python 文件所在目录不同。 将文件放在同一目录或子目录中是不够的。您还需要设置工作目录。或者,您可以创建一个绝对文件路径。


文件名和路径可以通过__file__获取。当前工作目录可以通过os.getcwd()获取,可以通过os.chdir(path)更改:

import os

os.chdir(os.path.dirname(os.path.abspath(__file__)))

另一种解决方案是找到绝对路径。 如果文件在 python 文件的子文件夹中(甚至在同一个文件夹中),那么您可以获取文件的目录并加入(os.path.join())相对文件路径。例如:

import pygame
import os

# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))

# [...]

# join the filepath and the filename
filePath = os.path.join(sourceFileDir, 'test_bg.jpg')
# filePath = os.path.join(sourceFileDir, '_pycache_/test_bg.jpg')

surface = pygame.image.load(filePath)

pathlib 模块也可以达到同样的效果。 更改工作目录

import os, pathlib

os.chdir(pathlib.Path(__file__).resolve().parent)

或创建一个绝对文件路径:

import pathlib

# [...]

filePath = pathlib.Path(__file__).resolve().parent / 'test_bg.jpg'
surface = pygame.image.load(filePath)

【讨论】:

以上是关于无法打开资源文件,pygame 错误:“FileNotFoundError:没有这样的文件或目录。”的主要内容,如果未能解决你的问题,请参考以下文章

Pygame:pygame.error:无法打开文件.ogg

Pygame Midi libasound_module_conf_pulse.so 错误 + 无法打开从站

pygame声音无法打开文件

无法打开包含文件:“SDL.h”

CompileAssemblyFromSource 返回错误“编译表达式:无法打开 c:\Users\*”以读取 'c:\Users\* 不是有效的 Win32 资源文件

无法使用 pip 安装 Pygame