John Applestein
John Applestein

Reputation: 93

Is there a way to know what files are in a folder and use them in Python?

I am building a GUI MP3 player. I want it so you put in mp3 files into a folder with the Python program, or even another place on the computer, and the program gets those files and plays them. Is there a way to do this? I have everything else except appending all the files in the folder into a list in my program.

Upvotes: 0

Views: 35

Answers (1)

CPTxShamrock
CPTxShamrock

Reputation: 99

try:

import os

####Creates music folder if necessary
def createMusicFolder():
    if 'music' not in os.listdir('.'):
        path = './music'
        os.mkdir(path)

##Lists files in your local dir
##Credit to CMU 15112 coursenotes
def listFiles(path):
    if os.path.isfile(path):
        return[path]
    else:
        files = []
        for filename in os.listdir(path):
            files += listFiles(path + '/' + filename)
        return files

createMusicFolder()
musicList = listFiles('./music')

this will create a music folder and then list all the files in the local dir. Then depending on what you're doing, you can use the files list to open whatever music

Upvotes: 1

Related Questions