首页 > 解决方案 > 如何在目录中随机显示每个文件一次,然后在我完成显示所有文件后再次显示

问题描述

这是一个音乐播放器模拟而不是播放歌曲我将打印我播放的每首歌曲的标题并获取目录中每个文件的位置

import os 
import sys 
import time 
import random 
import logging


# main: this is the main function of this Python
# def main(argv):
    count=c=1
    #make the program run for ever
    while True:
        #get the files from the comand line arguments 
        #check if the file end with mp3
        songs =  [f for f in os.listdir(sys.argv[1]) if f.endswith('.mp3')]
        #get the total number of files
        for (i, file) in enumerate(songs,1):
            #randamly select a song
            file = random.choice(songs)
            print ("{} ({},{}):playing file {}".format (count ,i , c ,file))
            count+=1
            #
            time.sleep(3)
        c+=1   

# begin gracefully
# if __name__ == "__main__":
    main(sys.argv)

标签: python

解决方案


您可能必须查看pathlibpython 模块。

要从某个路径获取所有 mp3 文件的列表,您可以尝试:

from pathlib import Path
mp3_files = list(Path("your/path").glob("**/*.mp3"))

您正在while循环中找到文件,这不是很有效的事情。其次,为什么需要第二个 for 循环?

编辑

因为你说,你不想播放已经播放过的文件。我建议看一下set数据结构。

mp3_files = set(mp3_files)

#select randomly somefile from the set
selected_file = mp3_files.pop()

该功能pop不仅会任意选择一个文件,还会将其从集合中删除。您不必跟踪已经播放过的文件。

编辑#2

把所有东西放在一起

def main():
    mp3_files = set(Path("your/path").glob("**/*.mp3")
    while True:
        selected_file = mp3_files.pop()

推荐阅读