Renaming a file to match parent folder name in Python 2.x.x

I keep all of my movies on a home NAS and don’t even remember the last time I used an actual disc to watch a movie.  I currently use MakeMKV (runs in Linux beautifully) to dump the films to my organized folder structure.  However, the file names it produces are usually not what I’m looking for – things like title00.mkv.  However, if there are multiple files in a folder, I generally want these to be left alone as they are usually extras (behind the scenes, interviews, that sort of thing).  So, I wrote a quick little app in Python to walk my directory structure, and if it finds a single file within a folder, it renames the file to match the parent folder name.  Now “title00.mkv” becomes “Blade Runner.mkv”.

 

This code runs in Python 2.x.x, hope someone finds this useful.  It will accommodate spaces in your paths in all OSes.  Simple to use, just provide the absolute path (from the root) via the ROOT_DIR variable.  It will begin in this folder and recursively walk/rename.  In Windows this path might look like:

ROOT_DIR = r’c:\users\yourusername\Desktop\media_folder’

 

#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Folder to Filename v1.0:  For Python 2.x.x
Scott C. King (revisionx at {gee}ma1l <dot> c0m).

Programs always presented with perfect Pylint score.
Pylint:  http://www.pylint.org/


Walks a directory structure, and if there is one file in a folder,
it renames the file (preserving extension) to the name of the folder.

'''

import os


ROOT_DIR = r'/path/to/parent'  # Absolute path to parent folder

def main():
    ''' Recursively walk root path.
        When only one file inside folder,
        Rename file to match parent folder name. '''

    op_sys = True
    if os.name == 'nt':
        op_sys = False

    for rootpath, _, files in os.walk(ROOT_DIR, followlinks=False):
        if len(files) == 1:

            original = rootpath + '/' + files[0]
            if not op_sys:
                original = rootpath + '\\' + files[0]

            print 'Original: {}'.format(original)
            ext = original.split('.')[-1]

            new = rootpath + '/' + rootpath.split('/')[-1] + '.' + ext
            if not op_sys:
                new = rootpath + '\\' + rootpath.split('\\')[-1] + '.' + ext

            if original == new:
                print 'Filename matches folder name.\n'
                continue
            else:
                print 'Renaming to: {}'.format(new)
                try:
                    os.rename(original, new)
                    print 'Success.'
                except OSError:
                    print 'Failed!'
            print '\n'


if __name__ == '__main__':
    main()

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.