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
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
...
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'))