解決第一個問題
阿新 • • 發佈:2018-12-10
我想要一款程式來備份我所有的重要檔案。
分析 + 設計
* 需要備份的檔案與目錄應在一份列表中予以指定。 * 備份必須儲存在一個主備份目錄中。 * 備份檔案將打包壓縮成 zip 檔案。 * zip 壓縮檔案的檔名由當前日期與時間構成。 * 我們使用在任何 GNU/Linux 或 Unix 發行版中都會預設提供的標準 zip 命令進行打包。在這裡你需要了解到只要有命令列介面,你就可以使用任何需要用到的壓縮或歸檔命令。
import os
import time
source =['/Users/keith/Desktop']
target_dir = '/Users/keith/Desktop/test'
target = target_dir + os.sep + \time.strftime('%Y%m%d%H%M%S') + '.zip'
if not os.path.exists(target_dir):
os.mkdir(target_dir)
zip_command = 'zip - r{0}{1}'.format(target,'',join(source))
print('Zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print ('Successful backup to',target)
else:
print('Backup Failed')
import os
import time
# 1. 需要備份的檔案與目錄將被
# 指定在一個列表中。
# 例如在 Windows 下:
# source = ['"C:\\My Documents"', 'C:\\Code']
# 又例如在 Mac OS X 與 Linux 下:
source = ['/Users/swa/notes']
# 在這裡要注意到我們必須在字串中使用雙引號
# 用以括起其中包含空格的名稱。
# 2. 備份檔案必須儲存在一個
# 主備份目錄中
# 例如在 Windows 下:
# target_dir = 'E:\\Backup'
# 又例如在 Mac OS X 和 Linux 下:
target_dir = '/Users/swa/backup'
# 要記得將這裡的目錄地址修改至你將使用的路徑
# 如果目標目錄不存在則建立目錄
if not os.path.exists(target_dir):
os.mkdir(target_dir) # 建立目錄
# 3. 備份檔案將打包壓縮成 zip 檔案。
# 4. 將當前日期作為主備份目錄下的子目錄名稱
today = target_dir + os.sep + time.strftime('%Y%m%d')
# 將當前時間作為 zip 檔案的檔名
now = time.strftime('%H%M%S')
# zip 檔名稱格式
target = today + os.sep + now + '.zip'
# 如果子目錄尚不存在則建立一個
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)
# 5. 我們使用 zip 命令將檔案打包成 zip 格式
zip_command = 'zip -r {0} {1}'.format(target,
' '.join(source))
# 執行備份
print('Zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')