Skip to content

Instantly share code, notes, and snippets.

@djt5019
Created October 18, 2012 00:05
Show Gist options
  • Save djt5019/3909112 to your computer and use it in GitHub Desktop.
Save djt5019/3909112 to your computer and use it in GitHub Desktop.
Playlist cleanup
#!/usr/bin/python
'''
Creates a .pls file for a given directory by default. If the options
-m or --m3u are given then a .m3u playlist is created.
NOTE:
* music files must be numbered, with space before name of song
* playlist will use the current directory if no arguments are given
* playlist takes only the first argument for the working directory
* playlist will read from stdin (a pipe), but returns no stdout
* playlist will ignore the argument if both argument and pipe are given
'''
import os
import sys
import optparse
FORMATS = set(['.mp3', '.flac', '.wma', '.ogg'])
def get_songs(path):
return [os.path.join(path, song) for song in os.listdir(path)
if get_extenstion(song) in FORMATS]
def get_extenstion(song):
return os.path.splitext(song)[1]
def make_playlist_from(location, m3u):
songs = get_songs(location)
if not songs:
raise Exception('No songs were found in {0}'.format(location))
if m3u:
extension = ".m3u"
preamble = '#EXTM3U\n'
line = '#EXTINF:-1,{song}\n{song}\n'
else:
extension = ".pls"
preamble = '[playlist]\nNumberOfEntries={0}\n'.format(len(songs))
line = 'File{index}={song}\n'
playlist_filename = os.path.basename(location) + extension
create_playlist(playlist_filename, preamble, line, songs)
def create_playlist(filename, preamble, line, songs):
with open(filename, 'w') as playlist:
playlist.writelines(preamble)
for index, song in enumerate(songs):
output = line.format(song=song, index=index)
playlist.write(output)
def valid_location(location):
return os.path.exists(os.path.abspath(os.path.expanduser(location)))
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option(
"-m", "--m3u", action="store_true", dest="m3uformat", default=False,
help="write in .m3u playlist format"
)
(options, args) = parser.parse_args()
if args and not isinstance(args, list):
args = map(valid_location, [args])
elif not args and not sys.stdin.isatty():
args = [sys.stdin.read()[:-1]]
elif not args:
args = [os.getcwd()]
locations = [location for location in args if valid_location(location)]
for location in locations:
make_playlist_from(location, options.m3uformat)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment