Keith Keith - 5 months ago 36
Python Question

Rename/Backup old directory in python

I have a script that creates a new directory regularly. I would like to check if it already exists and if so move the existing folder to a backup. My first iteration was

if os.path.isdir(destination_path):
os.rename(destination_path,destination_path + '_old')

However, if there already one being backed up it will obviously crash. What I would like to do is find the number of directories that match the destination_path and append that number like a version number.

if os.path.isdir(destination_path):
n = get_num_folders_like(destination_path)
os.rename(destination_path,destination_path + str(n))

I am just not sure how to make such a hypothetical function. I think fnmatch might work but I can't get the syntax right.


If you need to move the old directory aside, renumbering can easily be done by listing all directories by the same name, then picking last one by extracting the numeric maximum from the matching names.

Listing the directories can be done by using the glob module; it combines listing files with the fnmatch module to filter:

 import glob

if os.path.isdir(destination_path):
     # match all paths starting with the destination name, plus at least
     # an underscore and one digit.
     backups = glob.glob(destination_path + '_[0_9]*')
     def extract_number(path):
             # assume everything after `_` is a number
             return int(path.rpartition('_')[-1])
         except ValueError:
             # not everything was a number, skip this directory
             return None

     backup_numbers = (extract__number(b) for b in backups)
         next_backup = max(filter(None, backup_numbers)) + 1
     except ValueError:
         # no backup directories
         next_backup = 1

os.rename(destination_path,destination_path + '_{:d}'.format(next_backup))

I'm assuming you are not worried about race conditions here.