簡體   English   中英

使用Python腳本備份目錄

[英]Python Script to backup a directory

#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也被添加到環境變量下的Path和CLASSPATH中-非常歡迎其他建議備份目錄的人

也許可以使用名為rdiff-backup的python工具代替編寫自己的備份腳本,該工具可以創建增量備份?

source目錄包含空格,但是在命令行中沒有引號。 這可能是備份失敗的原因。

為了避免這樣的問題,使用subprocess模塊,而不是os.system

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

如果壓縮算法可以是其他壓縮算法,並且僅用於備份目錄,那么為什么不使用python自己的tar和gzip壓縮它呢? 例如

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()

這樣,您就不必依賴系統上的rar.exe

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM