python - 如何在目录中随机显示每个文件一次,然后在我完成显示所有文件后再次显示
问题描述
这是一个音乐播放器模拟而不是播放歌曲我将打印我播放的每首歌曲的标题并获取目录中每个文件的位置
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)
解决方案
您可能必须查看pathlib
python 模块。
要从某个路径获取所有 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()
推荐阅读
- html - 如何组织卡片组
- python - 从记录列表中过滤单元:BS4 Python
- docker - Docker .exe 甚至不会在 w10 企业版上启动
- javascript - 在应用程序外部调用路由更改(react-router)
- asp.net - 如何访问在 localhost (IIS) 上运行的 ASP.NET Web api
- redux - 如何检查用户是否登录过一次?
- regex - python正则表达式从字符串中删除特定的sub_string
- javascript - 将 Vue.js appstate 保存到本地存储的最佳事件
- windows - 在 Windows 2012 R2 Server 的 Hyper-V 上运行 Ubuntu 18.04 时出现黑色矩形并部分混淆桌面
- karate - 空手道 API 测试 - API 响应数组上的数值验证