Taming Your Music Collection: File Structure

Listing The Files
     Looking at our plan, the first task we need to tackle is passing a directory to the program, telling it where to begin its journey. Let's get the basic structure of our Python program started and add the code to accept a command line argument for the directory:
Code:
#!/usr/bin/python

import sys, os, argparse

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('-d', '--directory', nargs=1, required=True, help='')

    args = parser.parse_args()

    directory = os.path.abspath(args.directory[0])

main()
     Now our application accepts input from the user to choose the directory from which it should read. For information on using ArgumentParser, check out http://docs.python.org/library/argparse.html. I also used os.path.abspath() to ensure I am always getting an absolute path to where I want to be. You can find information on the os functions at http://docs.python.org/library/os.html. Next on our list, we need to be able to look into any sub-folders and iterate over any mp3 files we should find. To do this, we will use the os library again, as well as a pattern matching library called fnmatch.
Code:
#!/usr/bin/python

import sys, os, fnmatch, argparse

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('-d', '--directory', nargs=1, required=True, help='')

    args = parser.parse_args()

    directory = os.path.abspath(args.directory[0])

    for root, subFolders, filenames in os.walk(directory):
        for filename in fnmatch.filter(filenames, '*.mp3'):
            print os.path.join(root, filename)

main()
Result:
$ ./mp3-tagger.py -d /Music/Ghosts\ I\ mp3/
/Music/Ghosts I mp3/07 Ghosts I.mp3
/Music/Ghosts I mp3/04 Ghosts I.mp3
/Music/Ghosts I mp3/09 Ghosts I.mp3
/Music/Ghosts I mp3/08 Ghosts I.mp3
/Music/Ghosts I mp3/01 Ghosts I.mp3
/Music/Ghosts I mp3/03 Ghosts I.mp3
/Music/Ghosts I mp3/02 Ghosts I.mp3
/Music/Ghosts I mp3/05 Ghosts I.mp3
/Music/Ghosts I mp3/06 Ghosts I.mp3
     Now our application is able to iterate through any folders and sub-folders in our directory and look at any mp3 files it encounters. Eventually, we'll want to make it do something more than just print the file path, but for now we’ll just print the path to show it is working. To learn about how the fnmatch library works, you can visit http://docs.python.org/library/fnmatch.html.



;