【发布时间】:2015-01-27 15:41:12
【问题描述】:
我一直在尝试为我的兄弟制作一个程序。其中一个组件是播放音频文件。我有一个大约 90 个音频文件的列表(请不要问我为什么有 90 个),我正在尝试随机选择一个并播放它。但是,要播放它,我必须找到它的路径,然后将路径插入我的代码的另一部分(我仍在修复中)。这是我目前所拥有的:
import os, random
audio_playlist = [1, 2, 3, 4, ... all the way to 90]
sel_song = random.choice(audio_playlist)
song_path = None
base_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"songs")
现在,这就是我创建随机选择歌曲路径的方式:
while song_path == None:
if sel_song == 1:
song_path = os.path.join(directory, "1.mp3")
elif sel_song == 2:
song_path = os.path.join(directory, "2.mp3")
# and i do this 90 times... :(
有没有更 Pythonic 的方式来做到这一点?另外,我该如何做才能设置歌曲的路径,这样我就不必编写数百行代码,而是使用非常简单的东西,只有大约 10-15 行代码。另请注意,song_path 中的文件基本上只是带有.mp3 的数字,为简单起见。
【问题讨论】:
-
为什么不
s.path.join(directory, "{}.mp3".format(sel_song))? -
还有:
audio_playlist = [1, 2, 3, 4, ... all the way to 90]可以写成audio_playlist = range(1, 91) -
哇!那真的很快!这救了我!
-
@Zizouz212 硬编码“90”和命名方案从来都不是一个好主意。更好的办法是找出那里有哪些音频文件(使用
glob之类的东西),然后使用choice随机获取一个。这样做不会破坏您现在拥有的任何东西(它将继续使用您现在拥有的文件)。但是您的代码会更健壮,以后添加文件会容易得多。
标签: python list filepath os.path