在Python中,如何获得modu中文件目录的路径

2024-09-27 00:11:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个名为“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.pathpathlib尝试了许多不同的方法。我也尝试了不同的方法来使用module.__file__

任何帮助都将不胜感激!你知道吗


Tags: 模块文件path方法import目录playos
2条回答

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')

python3.7+中的解决方案是^{},或<;3.7的后端口^{}

# py 3.7

import os, subprocess
from importlib.resources import path

def play(sound=0):
    with path('playr', 'sounds') as p:
        sounds_path = p
    sounds = os.listdir(sounds_path)
    audio_file = os.path.join(sounds_path, sounds[sound])
    return_code = subprocess.call(['afplay', audio_file])

相关问题 更多 >

    热门问题