You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python程序无法访问子目录中的音频及其他文件问题求助

问题:调整音频文件目录后的Path路径适配问题

原有Python函数通过Path(__file__).with_name(sound_file)实现了从任意目录运行时找到程序目录下的音频文件并循环播放。现在需要将音频文件迁移到程序目录下的sound子目录(目录结构:app_dir\sound\),但调整Path路径时出现TypeError: Path.replace() takes 2 positional arguments but 3 were given错误,同时需要保证跨平台兼容性(当前使用Windows系统)。

原有核心代码片段:

def sound_player_loop(sound_file):
    # a sound player function which plays sound_file asynchronously on a continuous loop
    try:
        
        p = Path(__file__).with_name(sound_file)
        with p.open('rb') as sound:
            
    if sound.readable():
                winsound.PlaySound(str(p), winsound.SND_FILENAME | winsound.SND_LOOP | winsound.SND_ASYNC)
    
    except FileNotFoundError:
        print(f"{sound_file} not found in directory path.")
        pause()

尝试的错误代码:

sound_folder = Path("sound/")
file_to_play = sound_folder / sound_file
p = Path(__file__).with_name(file_to_play)

解决方案

问题根源

Path.with_name()方法的作用是替换路径中的文件名,只能接收字符串格式的文件名,不能传入完整的路径对象,这是导致报错的原因。要定位到sound子目录下的文件,应该先获取程序所在的目录,再拼接子目录和文件名。

修正后的完整代码

from pathlib import Path
import winsound
from time import pause  # 确保导入pause函数

def sound_player_loop(sound_file):
    # 异步循环播放音频文件的函数
    try:
        # 获取程序所在目录,拼接sound子目录和目标音频文件
        app_dir = Path(__file__).parent
        sound_path = app_dir / "sound" / sound_file
        
        with sound_path.open('rb') as sound:
            if sound.readable():
                winsound.PlaySound(str(sound_path), winsound.SND_FILENAME | winsound.SND_LOOP | winsound.SND_ASYNC)
    
    except FileNotFoundError:
        print(f"{sound_file} not found in sound directory.")
        pause()

关键说明

  1. 跨平台兼容性:使用Path对象的/操作符会自动适配Windows(\)和类Unix(/)系统的路径分隔符,无需手动处理。
  2. 路径定位逻辑:Path(__file__).parent获取当前Python文件所在的目录(即app_dir),再通过/ "sound" / sound_file拼接出完整的音频文件路径。
  3. 修复缩进问题:原有代码中if sound.readable():的缩进错误已修正,确保代码语法正确。

内容的提问来源于stack exchange,提问作者misfit138

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:05:14