歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python:實現文件歸檔

Python:實現文件歸檔

日期:2017/3/1 10:32:38   编辑:Linux編程
初學python,整理了下書上的例程,做為學習的第一個實用程序。 [python]
  1. #!/usr/bin/pyhton
  2. #Filename: backup.py
  3. #功能說明:備份文件,以當前日期為子目錄存放備份後的文件
  4. import os
  5. import time
  6. #要備份的目錄,可在此列表中增加
  7. source = [r'E:\360Downloads']
  8. #備份文件存放的目錄
  9. target_dir = 'E:\\backup\\'
  10. #取當前時間為備份子目錄名
  11. today = target_dir + time.strftime('%Y%m%d')
  12. now = time.strftime('%H%M%S')
  13. #在備份文件名中加入注釋
  14. comment = input('Enter a comment:')
  15. if len(comment) == 0:
  16. target = today + os.sep + now + '.zip'
  17. else:
  18. target = today + os.sep + now + '_' + \
  19. comment.replace(' ', '_') + '.zip'
  20. #如果目標目錄不存在就創建
  21. if not os.path.exists(today):
  22. os.mkdir(today)
  23. print('Successfully created directory', today)
  24. #備份命令,可替換為7z, Linux下可改為tar等
  25. zip_command = "winrar a %s %s" %(target, ' '.join(source))
  26. #執行命令
  27. if os.system(zip_command) == 0:
  28. print('Successful backup to', target)
  29. else:
  30. print('Backup failed')
Copyright © Linux教程網 All Rights Reserved