Skip to content

Instantly share code, notes, and snippets.

@simonseo
Created April 3, 2018 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonseo/1aea75f55c2a1962416645d86a8142ca to your computer and use it in GitHub Desktop.
Save simonseo/1aea75f55c2a1962416645d86a8142ca to your computer and use it in GitHub Desktop.
Creates .m3u from all mp3 files in the current directory
# createM3U.py
# Creates .m3u from current directory
# Dependencies: mutagen
# Usage: put this script in a folder that has mp3 files. run in console like so:
# $ python3 createM3U.py
# or
# $ python3 createM3U.py <path to mp3s>
from mutagen.id3 import ID3
from mutagen.mp3 import MP3
import sys, os, codecs, unicodedata
def main():
if len(sys.argv) > 1:
try:
os.chdir(sys.argv[1])
except Exception as e:
print("Invalid Folder.")
raise e
cwd = os.getcwd()
m3ufilename = os.path.basename(cwd) #name of folder this script is in
m3u = codecs.open(m3ufilename+".m3u", "w", "utf-16")
m3u.write("#EXTM3U\n\n") # m3u header
for root, dirs, files in os.walk(cwd):
for name in files:
name = unicodedata.normalize('NFC', name)
if name.endswith('.mp3'):
mp3info = MP3(name)
id3info = ID3(name)
d = {
"length" : str(int(mp3info.info.length)), # length in seconds
"artist" : id3info.get('TPE1').text[0], # first artist's name
"title" : id3info.get('TIT2').text[0], # title of song
"filename" : os.path.join(root.lstrip(cwd), name) # relative path from current directory
}
m3u.write("#EXTINF:{length}, {artist} - {title}\n{filename}\n".format(**d))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment