Skip to content

Instantly share code, notes, and snippets.

@torbiak
Last active November 8, 2017 06:57
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 torbiak/6316528 to your computer and use it in GitHub Desktop.
Save torbiak/6316528 to your computer and use it in GitHub Desktop.
Tag ogg, flac, and mp3 files with their Windows creation time.
#!/usr/bin/python
# Tag mp3, ogg, and flac files with a 'created' tag in the format 'YYYYMMDD',
# based on the file's birthtime, as stored by Windows. Unix doesn't store
# birthtimes, so this won't work there.
import os
import sys
from time import strftime, localtime
import mutagen # v1.21 works. Others probably do, too.
import traceback
verbose = False
def birthtime(filepath):
btime = os.stat(filepath).st_birthtime # birthtime is Windows-specific
return unicode(strftime('%Y%m%d', localtime(btime)))
def tag_mp3(filepath, created_at, update):
f = mutagen.File(filepath)
if u'TXXX:CREATED' not in f or update:
tag = mutagen.id3.TXXX(encoding=3, desc=u'CREATED', text=[created_at])
f[u'TXXX:CREATED'] = tag
f.save()
if verbose:
print 'CREATED=%s' % created_at
# flac and ogg
def tag_sane(filepath, created_at, update):
f = mutagen.File(filepath)
if u'created' not in f:
f[u'created'] = created
f.save()
if verbose:
print 'CREATED=%s' % created_at
def tag(filepath, created, update=False):
try:
if filepath.lower().endswith(('.ogg', '.flac')):
tag_sane(filepath, created, update)
elif filepath.lower().endswith('.mp3'):
tag_mp3(filepath, created, update)
except:
traceback.print_exc()
print 'Error, cannot tag %s' % filepath
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser("%prog [options] [path]...")
parser.add_option('-v', '--verbose', action='store_true')
parser.add_option('-u', '--update', action='store_true')
parser.add_option('-d', '--date')
(options, args) = parser.parse_args()
verbose = options.verbose
locs = args
if not locs:
sys.stdout.write('No files given.\n')
for loc in locs:
if os.path.isdir(loc):
for dirpath, dirs, files in os.walk(loc):
for filename in files:
filepath = os.path.join(dirpath, filename)
if verbose and filepath.endswith(('.ogg', '.flac', '.mp3')):
print filepath
created_at = options.date
if not created_at:
created_at = birthtime(filepath)
tag(filepath, created_at, options.update)
elif os.path.isfile(loc):
if verbose:
print loc
created_at = options.date
if not created_at:
created_at = birthtime(loc)
tag(loc, created_at, options.update)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment