python 尽管脚本和纹理文件夹在同一个文件夹中,但仍出现文件未找到错误

nhaq1z21  于 2023-06-20  发布在  Python
关注(0)|答案(3)|浏览(114)

当我输入以下代码时,它报告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:上的文件。

v7pvogib

v7pvogib1#

使用
background = pygame.image.load("./Art/base_vision.jpg")
./会让你的程序知道它是一个相对路径,并使用你当前的工作目录

xkftehaa

xkftehaa2#

你需要告诉python使用当前脚本的路径并将其与图像相对路径连接。

import os
script_directory = os.path.dirname(__file__)
image_relative_path = 'Art\\base_vision.jpg'
background = pygame.image.load(os.path.join(script_directory , image_relative_path))

每当你在脚本中写入__file__时,它总是会有这个变量所在文件的绝对路径。
如果你没有指定C:\users\...文件的绝对路径,那么python将查找相对于你当前工作目录what is current working directory的文件。

83qze16e

83qze16e3#

Python内置的pathlib库很好地解决了这个问题。下面是一个示例,说明script.py在给定您所描述的文件夹结构的情况下,www.example.com的外观

Game/
├─ Pygame test/
│  ├─ script.py
│  ├─ Art/
│  │  ├─ art.png
from pathlib import Path

import pygame

SCRIPT_PATH = Path(__file__).resolve() # get the path of the script
PYGAME_PATH = SCRIPT_PATH.parents[0] # parents gives a list of parent directories, get the first one
ART_PATH = PYGAME_PATH / "Art" # the division operator for Path objects concatenates a Path object with a string

background = pygame.image.load(ART_PATH / "art.png")

大多数库都接受Path对象,但如果它们不接受,您可以通过调用as_posix方法PATH_OBJECT.as_posix()将它们转换回字符串。
还要注意的是,在处理路径时,你不应该使用反斜杠。反斜杠在Python中作为转义符有特殊的含义。Python足够聪明,可以正确地解释正斜杠,即使在Windows上也是如此(但是使用Path对象几乎是跨平台的,并且还提供了一系列方便的函数)。

相关问题