python學習之路-第三天-一個簡單的指令碼

來源:互聯網
上載者:User

標籤:log   htm   推薦   .com   建立   檔案目錄   ack   window   lib   

現在有一個需求:把某個目錄下的檔案備份到指定到另外一個目錄下,而且壓縮後檔案為zip檔案
# -*- coding:utf-8 -*-#! /usr/bin/python# Filename:backup_v1.pyimport osimport timesource = [r‘H:\StudyLib\lib‘]# 源檔案目錄,是個列表,可以放入多個目錄target_dir = ‘I:\\backpacks\\‘# 目標目錄target = target_dir + time.strftime(‘%Y%m%d%H%M%S‘) + ‘.zip‘# 目標zip檔案zip_commend = "zip -qr %s %s" % (target, ‘ ‘.join(source))# zip命令字串print zip_commend#輸出命令列測試if os.system(zip_commend) == 0:# 執行zip命令,若返回0,則說明正確備份    print ‘Successful backup to ‘ ,targetelse:    print ‘backup failed‘

上面的注釋寫的挺詳細的了,我們需要注意的由兩點:

一個是windows不會內建zip壓縮程式,需要我們自己下載,並把環境變數配置正確,

另一個如果沒有在頭部聲明編碼的話會出現中文編碼的問題,一定要寫在第一行

這個版本其實只是把源檔案和目標檔案規定了一下,並沒有任何最佳化操作

第一個最佳化:

可以在我們的目標目錄中建立一級和二級目錄,一級目錄名稱就為年月日,這樣在每次做備份的時候,可以確保一天只建立一個檔案夾(如果存在就不用建立新的檔案夾了)

# -*- coding:utf-8 -*-#! /usr/bin/python# Filename:backup_v1.pyimport osimport timesource = [r‘H:\StudyLib\lib‘]# 源檔案目錄,是個列表,可以放入多個目錄target_dir = ‘I:\\backpacks\\‘# 目標目錄today = target_dir + time.strftime(‘%Y%m%d‘)# 目標檔案夾的一級目錄now = time.strftime(‘%H%M%S‘)# 目標檔案夾的二級目錄if not os.path.exists(today):    os.mkdir(today)    print ‘Successful create directory‘,today# 如果目錄不存在則建立target = today + os.sep + now + ‘.zip‘# 目標檔案zip_commend = "zip -qr %s %s" % (target, ‘ ‘.join(source))# zip命令字串print "執行命令:" +zip_commend#輸出命令列測試if os.system(zip_commend) == 0:                               # 執行zip命令,若返回0,則說明正確備份    print ‘Successful backup to ‘ ,targetelse:    print ‘backup failed‘
最理想的建立這些歸檔的方法是分別使用zipfile和tarfile,因為是python標準庫裡面的方法,這次的學習裡面的os.system方法就不推薦使用

python學習之路-第三天-一個簡單的指令碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.