[英]Pygame Error : FileNotFoundError: No such file or directory. They are already in the same folder
I'm new to programming, and this error keeps popping up no matter what.我是编程新手,无论如何都会弹出这个错误。 I tried changing the file to something else, or moving all the things altogether.
我尝试将文件更改为其他文件,或者将所有文件一起移动。 They are in the same folder.
它们在同一个文件夹中。 Here's the code:
这是代码:
import pygame
import os
import time
import random
pygame.font.init()
pygame.init()
WIDTH, HEIGHT = 750, 750
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Shooter Tutorial")
# Sounds
bulletSound = pygame.mixer.Sound("bullet.wav")
hitSound = pygame.mixer.Sound("hit.wav")
music = pygame.mixer.music.load("music.wav")
pygame.mixer.music.play(-1) # -1 will make the song loop
# Load images
RED_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_red_small.png"))
GREEN_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_green_small.png"))
BLUE_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_blue_small.png"))import pygame
import os
import time
import random
pygame.font.init()
pygame.init()
WIDTH, HEIGHT = 750, 750
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Shooter Tutorial")
# Sounds
bulletSound = pygame.mixer.Sound("bullet.wav")
hitSound = pygame.mixer.Sound("hit.wav")
music = pygame.mixer.music.load("music.wav")
pygame.mixer.music.play(-1) # -1 will make the song loop
# Load images
RED_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_red_small.png"))
GREEN_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_green_small.png"))
BLUE_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_blue_small.png"))
The trouble come when I run it, and they say:当我运行它时,麻烦来了,他们说:
Traceback (most recent call last): File "/Users/abhivyaktbhati/Desktop/PYTHON NOW/assets/Draft with sounds.py", line 20, in <module> RED_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_red_small.png")) FileNotFoundError: No such file or directory.
How to fix this?如何解决这个问题? PS.
附言。 This is on a mac.
这是在 Mac 上。
The file path has to be relative to the current working directory.文件路径必须相对于当前工作目录。 The working directory is possibly different form the directory of the source files.
工作目录可能与源文件的目录不同。
One solution is to change the working directory.一种解决方案是更改工作目录。 The name and path of the file can be get by
__file__
.文件的名称和路径可以通过
__file__
获取。 The current working directory can be get by os.getcwd()
and can be changed by os.chdir(path)
.当前工作目录可以通过
os.getcwd()
获取,也可以通过os.chdir(path)
更改。 Put the following code at the begin of your application:将以下代码放在应用程序的开头:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.