backup_ver2.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import os
  2. import time
  3. # 1. The files and directories to be backed up are
  4. # specified in a list.
  5. # Example on Windows:
  6. # source = ['"C:\\My Documents"', 'C:\\Code']
  7. # Example on Mac OS X and Linux:
  8. source = ['/Users/swa/notes']
  9. # Notice we had to use double quotes inside the string
  10. # for names with spaces in it.
  11. # 2. The backup must be stored in a
  12. # main backup directory
  13. # Example on Windows:
  14. # target_dir = 'E:\\Backup'
  15. # Example on Mac OS X and Linux:
  16. target_dir = '/Users/swa/backup'
  17. # Remember to change this to which folder you will be using
  18. # Create target directory if it is not present
  19. if not os.path.exists(target_dir):
  20. os.mkdir(target_dir) # make directory
  21. # 3. The files are backed up into a zip file.
  22. # 4. The current day is the name of the subdirectory
  23. # in the main directory.
  24. today = target_dir + os.sep + time.strftime('%Y%m%d')
  25. # The current time is the name of the zip archive.
  26. now = time.strftime('%H%M%S')
  27. # The name of the zip file
  28. target = today + os.sep + now + '.zip'
  29. # Create the subdirectory if it isn't already there
  30. if not os.path.exists(today):
  31. os.mkdir(today)
  32. print 'Successfully created directory', today
  33. # 5. We use the zip command to put the files in a zip archive
  34. zip_command = "zip -r {0} {1}".format(target,
  35. ' '.join(source))
  36. # Run the backup
  37. print "Zip command is:"
  38. print zip_command
  39. print "Running:"
  40. if os.system(zip_command) == 0:
  41. print 'Successful backup to', target
  42. else:
  43. print 'Backup FAILED'