python学习:备份文档并压缩为zip格式

import os
import time

source = ['/root/notes']

target_dir = '/root/backup'

if not os.path.exists(target_dir):
    os.mkdir(target_dir)

today = target_dir+os.sep+time.strftime('%Y%m%d')

now = time.strftime('%H%M%S')

target=today+os.sep+now+'.zip'

if not os.path.exists(today):
    os.mkdir(today)
    print('Successfully created directory',today)

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

执行结果:

[root@localhost ~]# python backup.py
('Successfully created directory', '/root/backup/20170918')
Zip command is:
zip -r /root/backup/20170918/232132.zip /root/notes
Running:
adding: root/notes/ (stored 0%)
adding: root/notes/meminfo.py (deflated 41%)
adding: root/notes/__init__.py (stored 0%)
adding: root/notes/zidianpaixu.py (deflated 45%)
adding: root/notes/16.py (deflated 42%)
adding: root/notes/5.py (deflated 26%)
adding: root/notes/dmi.py (deflated 50%)
adding: root/notes/collect_info.py (deflated 68%)
adding: root/notes/dmi2.py (deflated 50%)
adding: root/notes/12.py (deflated 25%)
adding: root/notes/printpid2.py (deflated 34%)
adding: root/notes/11.py (deflated 11%)
adding: root/notes/8.py (deflated 57%)
adding: root/notes/printpid.py (deflated 41%)
adding: root/notes/10.py (deflated 7%)
adding: root/notes/ifconfig.py (deflated 39%)
adding: root/notes/13_ip.py (deflated 53%)
adding: root/notes/13.py (deflated 20%)
adding: root/notes/wc.py (deflated 31%)
adding: root/notes/4.py (deflated 32%)
adding: root/notes/15.py (deflated 39%)
('Successful backup to', '/root/backup/20170918/232132.zip')

原文地址:https://www.cnblogs.com/weifeng1463/p/7550758.html