Reading The ID3 Info
Now we need to read the actual id3 data from the files. We'll be using the Mutagen module mentioned earlier, and more specifically, the EasyID3 package. We can also use this package to modify the existing id3 data. We will use it to remove tags we don't want, such as the genre tag. We'll make a new function in preparation for one of our eventual operations: moving the file to its new location.
Code:
Now we need to read the actual id3 data from the files. We'll be using the Mutagen module mentioned earlier, and more specifically, the EasyID3 package. We can also use this package to modify the existing id3 data. We will use it to remove tags we don't want, such as the genre tag. We'll make a new function in preparation for one of our eventual operations: moving the file to its new location.
Code:
#!/usr/bin/python import sys, os, fnmatch, argparse from mutagen.easyid3 import EasyID3 def move(file): id3info = EasyID3(file) _trackNumber = id3info["tracknumber"][0] _artist = id3info["artist"][0] _title = id3info["title"][0] _album = id3info["album"][0] if "genre" in id3info: id3info["genre"] = u"" id3info.save() outputFile = _trackNumber + ". " + _artist + " - " + _title + ".mp3" print outputFile 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'): move(os.path.join(root, filename)) main()Result:
$ ./mp3-tagger.py -d /Music/Ghosts\ I\ mp3/ 7/36. Nine Inch Nails - 7 Ghosts I.mp3 4/36. Nine Inch Nails - 4 Ghosts I.mp3 9/36. Nine Inch Nails - 9 Ghosts I.mp3 8/36. Nine Inch Nails - 8 Ghosts I.mp3 1/36. Nine Inch Nails - 1 Ghosts I.mp3 3/36. Nine Inch Nails - 3 Ghosts I.mp3 2/36. Nine Inch Nails - 2 Ghosts I.mp3 5/36. Nine Inch Nails - 5 Ghosts I.mp3 6/36. Nine Inch Nails - 6 Ghosts I.mp3This will remove the genre tag from any mp3 that contains it and print our newly formatted file path. We want to make sure it works before we actually move the files.