英文:
Pygame not recognizing my path but VS Code does?
问题
**我的PYTHON版本是3.10**
**我的PYGAME版本是2.1.3**
我遇到了以下问题:
- 我正在使用pygame,更具体地说是mixer。在定义我想播放的文件的路径时,我遇到了以下错误:
`FileNotFoundError: 在工作目录'C:\Users\acmem\Desktop\programacion'中找不到文件'../Assets/Music/ability.mp3'。`
- 我理解路径肯定有问题,但是当我在使用mixer的文件中输入路径时,VS Code会识别文件夹结构,甚至提供自动完成我正在输入的路径(如果我输入'../',那么VSCODE会提供自动完成该级别文件夹结构中的文件夹)。出于某种我还不理解的原因,Python仍然告诉我找不到文件,但VS Code却找到了。
mixer文件的代码如下:
```python
import pygame
from pygame import mixer
pygame.init()
import colorama
from colorama import Fore
colorama.init()
def new_ability():
path = "../Assets/Music/ability.mp3"
pygame.mixer.init()
pygame.mixer.Sound(path).play()
文件夹结构如下:
JuegoTXT: Modules\abilities.py(mixer文件)
Assets\Music\ability.mp3(我想播放的文件)
感谢任何帮助,谢谢。
<details>
<summary>英文:</summary>
**MY *PYTHON* VERSION IS *3.10***
**MY *PYGAME* VERSION IS *2.1.3***
I have the following problem:
- I'm using pygame, more especifically mixer. When defining the path of the archive I want to play, I run into the following error:
`FileNotFoundError: No file '../Assets/Music/ability.mp3' found in working directory 'C:\Users\acmem\Desktop\programacion'.`
- I understand that there has to be some error with the path, of course, but when I'm tyoing the path in the file where I'm using mixer, VS Code recognizes the folder structure and even offers to auto-complete the path I'm writing (if I type '../', then VSCODE offers me to autocomplete with the folders in that level of the folder structure). For some reason I do not yet understand, python still tells me it cannot find the file but VS Code is.
The code of the mixer file is the following:
import pygame; from pygame import mixer; pygame.init(); import colorama; from colorama import Fore; colorama.init()
def new_ability():
path = "../Assets/Music/ability.mp3"
pygame.mixer.init()
pygame.mixer.Sound(path).play()
The folder structure is the following:
JuegoTXT: Modules\abilities.py (the mixer file)
Assets\Music\ability.mp3 (The file I want to play)
Any help is appreciated, thank you.
</details>
# 答案1
**得分**: 1
相对路径取决于你的工作文件夹,当你执行脚本时可能会有所不同,请尝试更改代码,使其绑定到实际的 Python 文件
...
import pathlib
root = pathlib.Path(__file__).parent
path = root / "../Assets/Music/ability.mp3"
<details>
<summary>英文:</summary>
Relative path depends on your working folder and could be different when you execute the script, try changing the code, so it is bound to the actual python file
...
import pathlib
root = pathlib.Path(__file__).parent
path = root / "../Assets/Music/ability.mp3"
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论