All pastes #2109227 Raw Edit

sortseries

public python v1 · immutable
#2109227 ·published 2012-02-03 08:31 UTC
rendered paste body
#!/usr/bin/env python# notes:# replacing 'the' might not work for everythingimport os, re, shutildef nogo( item, reason ):    print item + ' is a nogo: ' + reasonfrom_path = '/mnt/F4/Downloads'to_path = '/mnt/F4/Serier'# get all series dirsto_contents = {}for item in os.listdir( to_path ):    matchname = re.sub( '\W', '' , item.lower().replace( 'the', '' ) )    # matchname: slugified name to be matched with downloaded files    to_contents[matchname] = itemfor item in os.listdir( from_path ):    oldpath = os.path.join( from_path, item )    #remove = oldpath # for rm of dirs    matches = re.findall( '^(.*?)se?(\d{1,2})ep?\d{1,2}', item.lower() )    if not matches:        continue    show_name = matches[0][0]    # remove non alphanumerics and 'the's for matching with existing dirs    show_name = re.sub( '\W', '' , show_name.replace( 'the', '' ) )    season = int( matches[0][1] )        # find the actual file if it's a dir    if os.path.isdir( oldpath ):        epcontents = os.listdir( oldpath )        eps = {}        for subitem in epcontents:            eps[ os.path.getsize( oldpath ) ] = subitem        # append the largest file in the dir to the old path        oldpath = os.path.join( oldpath, eps[ max( eps ) ] )        # do we have a dir for this show?    if not show_name in to_contents:        nogo( item, 'No matching show in storage location' )        continue        # get all seasons for this show    seasons = {}    seasonlist = os.listdir( os.path.join( to_path, to_contents[show_name] ) )    for s in seasonlist:            matches = re.findall( '\d+', s )            if matches:                seasons[ int( matches[0] ) ] = s    if not season in seasons:        nogo( item, 'No matching season in storage location' )        continue    # item should be moved    newpath = os.path.join( to_path, to_contents[show_name], seasons[season] )    newpathfile = os.path.join( newpath, item )    if os.path.isfile( newpathfile ):        nogo( item, 'File exists' )        continue    print item + ' -> ' + newpathfile    shutil.move( oldpath, newpath )    #shutil.copy2( oldpath, newpath )    #if os.path.isfile( newpathfile ):    #    # remove the old file / dir if the new is safe in place    #    if os.path.isfile( remove ):    #        os.remove( remove )    #    else:    #        # if its a dir we have to use this..    #        shutil.rmtree( remove )