簡體   English   中英

無法打開資源文件,pygame 錯誤:“FileNotFoundError:沒有這樣的文件或目錄。”

[英]Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."

Import pygame pygame.init() BG = pygame.image.load('_pycache_/test_bg.jpg') def DrawGameWin(): window.blit(BG,(0,0)) pygame.display.update() DrawGameWin()

資源(圖像、字體、聲音等)文件路徑必須相對於當前工作目錄。 工作目錄可能與 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)

為了捎帶Rabid76 的答案,在 Python 3.4 或更高版本中, pathlib模塊可以方便地使用一種語法來操作文件路徑,至少在我看來,它os更干凈、更容易

使用pathlib重寫代碼的后半部分如下所示:

from pathlib import Path

import pygame

# Get the directory of this file.
# .resolve() insures that it's an absolute path.
source_file_dir = Path(__file__).resolve().parent

# Join the filepath and the filename.
file_path = source_file_dir / 'test_bg.jpg'

surface = pygame.image.load(file_path)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM