当我输入以下代码时,它报告filenotfound错误:
background = pygame.image.load('Art/base_vision.jpg')
报告为No file 'Art/window_icon.png' found in working directory 'C:\Users\xxx'
然而,脚本的目录是c:/Users/xxx/Desktop/Game/Pygame test
,项目中使用的所有艺术品都在c:/Users/xxx/Desktop/Game/Pygame test/Art
中。它只是不会接受文件夹“Art
“中的文件,而是只接受C:/Users/xxx
中的文件。
这是我发送给团队成员的一个小组项目,因此脚本需要使用其文件夹中的文件,而不是C:
上的文件。
3条答案
按热度按时间v7pvogib1#
使用
background = pygame.image.load("./Art/base_vision.jpg")
./会让你的程序知道它是一个相对路径,并使用你当前的工作目录
xkftehaa2#
你需要告诉python使用当前脚本的路径并将其与图像相对路径连接。
每当你在脚本中写入
__file__
时,它总是会有这个变量所在文件的绝对路径。如果你没有指定
C:\users\...
文件的绝对路径,那么python将查找相对于你当前工作目录what is current working directory的文件。83qze16e3#
Python内置的
pathlib
库很好地解决了这个问题。下面是一个示例,说明script.py在给定您所描述的文件夹结构的情况下,www.example.com的外观大多数库都接受Path对象,但如果它们不接受,您可以通过调用as_posix方法
PATH_OBJECT.as_posix()
将它们转换回字符串。还要注意的是,在处理路径时,你不应该使用反斜杠。反斜杠在Python中作为转义符有特殊的含义。Python足够聪明,可以正确地解释正斜杠,即使在Windows上也是如此(但是使用Path对象几乎是跨平台的,并且还提供了一系列方便的函数)。