1

I am trying to make a function that copies all the directories and files and puts them in a folder. This directory does not have a backup folder, so the first time I make one using copy tree, and each time you re-run this program, it should back up again (including the prevrious backup). I am having a problem with copytree getting caught in a huge recursive loop and don't know what I am doing wrong. Here is my code. It works for the first time but when I run it a second time it messes up. argv[1] is a local folder you wish to backup. This would be run as:

% python3 filename foldername

from os import path, walk, remove, mkdir, listdir
from sys import argv
from shutil import copytree


    if path.exists(argv[1]+'/Versions'):
        copytree(argv[1], argv[1]+ '/Versions/' + str((len(listdir(argv[1]+'/Versions')))+1))

    else:

        copytree(argv[1], argv[1]+'/Versions/1')

If the Versions folder is already there, it counts the number of subfolders and creates a new folder with its label +1 the number of folders present

frosty
  • 307
  • 4
  • 15

1 Answers1

2

It looks to me you're creating your backup in a subfolder of the folder you're backing up.

So the next time you run your script, you're making a backup of a backup, and then a backup of a backup of a backup and so on

Put your backup into a location that isn't a subfolder of your original data, and your script should work.

source_path = os.path.join(argv[1], '/Versions')
destination_path = os.path.join(argv[1], '..', '/Backup') 

#Now handle copying between these two locations
...

Using Ignore method

Alternatively, you can pass in a callable to the copytree to ignore certain directories.

from shutil import copytree, ignore_patterns

copytree(source_path, destination_path, ignore=ignore_patterns('Versions'))
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • So there is no way I can do this with copytree with it being saved in a subfolder of the original data? – frosty Jun 06 '14 at 23:35
  • I updated my answer so you can store backup in a sub-folder if you need to. – Martin Konecny Jun 06 '14 at 23:41
  • The ignore method is exactly what I needed. I had read about it in the python libraries but was having trouble implementing it. Thanks man! – frosty Jun 06 '14 at 23:45