开发者

Python Script to backup a directory

开发者 https://www.devze.com 2022-12-23 06:39 出处:网络
#Filename:backup_ver1 import os import time #1 Using list to specify the files and directory to be backed up
#Filename:backup_ver1

import os
import time

#1 Using list to specify the files and directory to be backed up
source = r'C:\Documents and Settings\rgolwalkar\Desktop\Desktop\Dr Py\Final_Py'

#2 define backup directory
destination = r'C:\Documents and Settings\rgolwalkar\Desktop\Desktop\PyDevResourse'

#3 Setting the backup name
targetBackup = destination + time.strftime('%Y%m%d%H%M%S') + '.rar'

rar_command = "rar.exe a -ag '%s' %s" % (targetBackup, ''.join(source))
##i am sure i am doing something wrong here - rar command please let me know

if os.system(rar_command) == 0:
    print 'Successful backup to', targetBackup
else:
    print 'Backup FAILED'

O/P:- Backup FAILED

winrar is added to Path and CLASSPATH under Environment variables as well - anyone else with a suggestion for backing up the director开发者_开发知识库y is most welcome


Maybe instead of writing your own backup script you could use python tool called rdiff-backup, which can create incremental backups?


The source directory contains spaces, but you don't have quotes around it in the command line. This might be a reason for the backup to fail.

To avoid problems like this, use the subprocess module instead of os.system:

subprocess.call(['rar.exe', 'a', '-ag', targetBackup, source])


if the compression algorithm can be something else and its just to backup a directory, why not do it with python's own tar and gzip instead? eg

import os
import tarfile
import time
root="c:\\"
source=os.path.join(root,"Documents and Settings","rgolwalkar","Desktop","Desktop","Dr Py","Final_Py")
destination=os.path.join(root,"Documents and Settings","rgolwalkar","Desktop","Desktop","PyDevResourse")
targetBackup = destination + time.strftime('%Y%m%d%H%M%S') + 'tar.gz'    
tar = tarfile.open(targetBackup, "w:gz")
tar.add(source)
tar.close()

that way, you are not dependent on rar.exe on the system.

0

精彩评论

暂无评论...
验证码 换一张
取 消