![](/img/trans.png)
[英]How do I import python class from a module located within file directory named '@file_directory' or directory with special characters?
[英]In Python, how do I get the path to a directory of files located within a module
我创建了一个名为“playr”的模块,它有一个 wav 文件的子目录:
user/repositories/python_packages/playr/
|
|--__init__.py
|--sounds/
| |--sound1.wav
| |--sound2.wav
| |--sound3.wav
在我的__init__.py
是一个函数,它应该获取sounds/
目录中所有文件的列表,以便播放选定的声音:
from os import listdir
import os.path
import subprocess
def play(sound=0):
wav_files = listdir('sounds')
sound_file = os.path.join('sounds', wav_files[sound])
return_code = subprocess.call(['afplay', sound_file])
因为我想分享这个模块,所以我需要找到一种方法来获取到sounds/
目录的路径,而无需对绝对路径进行硬编码。 父目录user/repositories/python_packages/
包含在我的PYTHONPATH
变量中。
目前,当我尝试在不同目录中使用来自 python env 的模块时,它是这样的:
from playr import play
play()
----------------------------------------------------------------
FileNotFoundError: [Errno 2] No such file or directory: 'sounds'
我知道它没有找到sounds/
目录,因为它在我当前的环境中而不是在模块中查找。 我的问题是如何让我的函数在模块中而不是当前环境中查找。
到目前为止,我已经使用os.path
和pathlib
尝试了许多不同的方法。 我也尝试过使用module.__file__
不同方式
任何帮助将不胜感激!
python 3.7+ 中的解决方案是importlib.resources
,或者 < 3.7 的 backport importlib_resources
:
# py 3.7
import os, subprocess
from importlib.resources import path
def play(sound=0):
with path('playr', 'sounds') as sounds_path:
sounds = os.listdir(sounds_path)
audio_file = os.path.join(sounds_path, sounds[sound])
return_code = subprocess.call(['afplay', audio_file])
os.path.abspath(__file__)
返回当前模块文件的完整路径名,例如/foo/bar/baz/module.py
。
os.path.dirname(fullpath)
去掉文件名,只返回目录,即/foo/bar/baz
。
所以你要:
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sounds')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.