如何使用Python 3从文件夹/目录中搜索和播放mp3文件?
我想编写一个python代码,当给定要搜索的mp3文件的stringname时,它将搜索与给定字符串和文件名匹配的目录。找到后,它会打开并播放 我有一个代码,在给定的目录中搜索给定的字符串。是否可以修改此代码以实现上述任务?多谢各位`如何使用Python 3从文件夹/目录中搜索和播放mp3文件?,python,python-3.x,pygame,ubuntu-14.04,Python,Python 3.x,Pygame,Ubuntu 14.04,我想编写一个python代码,当给定要搜索的mp3文件的stringname时,它将搜索与给定字符串和文件名匹配的目录。找到后,它会打开并播放 我有一个代码,在给定的目录中搜索给定的字符串。是否可以修改此代码以实现上述任务?多谢各位` #Import os module import os # Ask the user to enter string to search search_path = input("Enter directory path to search : ") file_
#Import os module
import os
# Ask the user to enter string to search
search_path = input("Enter directory path to search : ")
file_type = input("File Type : ")
search_str = input("Enter the search string : ")
# Append a directory separator if not already present
if not (search_path.endswith("/") or search_path.endswith("\\") ):
search_path = search_path + "/"
# If path does not exist, set search path to current directory
if not os.path.exists(search_path):
search_path ="."
# Repeat for each file in the directory
for fname in os.listdir(path=search_path):
# Apply file type filter
if fname.endswith(file_type):
# Open file for reading
fo = open(search_path + fname)
# Read the first line from the file
line = fo.readline()
# Initialize counter for line number
line_no = 1
# Loop until EOF
while line != '' :
# Search for string in line
index = line.find(search_str)
if ( index != -1) :
print(fname, "[", line_no, ",", index, "] ", line, sep="")
# Read next line
line = fo.readline()
# Increment line counter
line_no += 1
# Close the files
fo.close()
这段代码有点不同,但最适合解决上述问题
!/usr/bin/env python3
import os
import random
import sys
rdm = raw_input("Would you let me make a choice? 0 or 1: ")
#cur_dir = os.getcwd()
if rdm == '1':
print("Playing random song")
folder=os.listdir(os.getcwd()) #To randomly play a song
file=random.choice(folder)
ext3=['.mp3']
print('First random pick: '+file)
while file[-4:] not in ext3 :
print('Not an MP3 file : '+file)
file=random.choice(folder)
else:
os.startfile(file)
print('Song name: '+file)
sys.exit()
else:
if rdm == '0':
file_name = raw_input("File Name: ") #file to be searched
#cur_dir = raw_input("Search Directory: ") # Dir from where search starts can be replaced with any path
cur_dir = os.getcwd()
while True:
file_list = os.listdir(cur_dir)
parent_dir = os.path.dirname(cur_dir)
if file_name in file_list:
print ("File Exists in: "), cur_dir
#
os.startfile(file_name)
#
break
else:
if cur_dir == parent_dir: #if dir is root dir
print ("File not found")
break
else:
cur_dir = parent_dir
找到文件后,os.startfile'filename.mp3'将播放该文件。使用os.startfile可以播放mp3,对吗?或者我需要pygame、pyglet或任何其他python媒体模块吗?使用glob.glob'*.mp3'获取匹配文件的列表。使用os.path.join将路径正确地连接在一起,而不必担心斜杠或反斜杠。这与您的问题无关,但在将来提问时需要考虑一些问题;不要包含解释代码行功能的注释。行导入操作系统不需要表示导入操作系统模块的注释,行_no+=1不需要表示增量行计数器的注释。它只会引入噪音,使阅读更加困难。当你觉得需要解释你的逻辑时,可以使用注释。理解代码的人不需要解释代码的注释,不理解代码的人也帮不了你。