1

Just as the title says i need to add a folder to a directory with a new name if it already has that name. i have this script that copy's a folder no problem but if run it again it fails because it already exists. is there a way i can just add the folder with a number attached to it like "backup1", "backup2", etc. Here is the script example:

import shutil
MAIN_DIR = r'Y:\A'
COPY_DIR = r'Y\B\Backup1'
shutil.copytree(MAIN_DIR,COPY_DIR)

Thank you for any help

Edit: Basically what i want is how to make a new folder and copy the contents there every time the script is run. like for example, check if backup1 exists if it does then make backup2, then copy contents to that directory. If i run it again check for backup2 if there make backup3, etc.

kytexaranort
  • 67
  • 1
  • 8
  • Possible duplicate of [How can I create a directory if it does not exist?](https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist) – divibisan May 08 '18 at 16:23

1 Answers1

0

I found the answer i was looking for, after about 9 hours of searching.

import os
index = ''
while True:
    try:
        os.makedirs('/hi'+index)
        break
    except WindowsError:
        if index:
            index = '('+str(int(index[1:-1])+1)+')' # Append 1 to number in brackets
        else:
            index = '(1)'
        pass

found answer here: https://stackoverflow.com/a/24996533/8116117

Basically it creates a folder then appends a number to it if it already exists. I worked the base functionality of the script into my own and it worked on first try then continuously 150 times after that without fail.

If this helps you up vote the person that posted in the link.

kytexaranort
  • 67
  • 1
  • 8