【Python】一个python实例:给重要的文件创建备份.摘自crossin-python简明教程

问题:写一个可以为所有重要文件创建备份的程序

考虑:源路径和目标路径各是什么;所有重要文件-有哪些;备份文件格式是什么;定期备份的话,备份文件名称如何规定等等。(ps,我自己只想到一个路径和名称)

程序设计:

  1 需要备份的文件和目录由一个列表指定

  2 备份应该保存在主备份目录中。?

  3 文件备份成一个tar文件(原文档为zip文件,我的linux没有安装,所以使用tar)

  4 tar存档的名称是当前的日期和时间

  5 使用标准的tar命令

Version1.0

#/usr/bin/python
#Filename:backup_ver1.py
#-*- coding:utf-8 -*-
import os
import time
#1 The files and directories to be backed up are specified in a list.
source=['/home/zhaoxiaodan/pythonTest/*','/home/zhaoxiaodan/javaTest']
#2 The backup must be stored in a main backup directory
target_dir='/opt/soft/backup_test/'
#3 The backup file is tar.gz ,and named with date
target=target_dir+time.strftime('%Y%m%d%H%M%S')+'.tar.gz'
#4 Use the tar.gz command
tar_command="tar cvf %s %s"%(target,' '.join(source))
if os.system(tar_command)==0:
        print 'Successful backup to %s'%target
else:
        print 'Failed'
结果:Successful backup to /opt/soft/backup_test/20151022171749.tar.gz

对压缩包解压的时候有如下问题

[root@bjdhj-120-× backup_test]# tar -xzvf 20151022164024.tar.gz 

gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now

查了一下说是压缩包没有用gzip格式压缩  所以解压的时候也不用加上z 。直接tar -xf 就可以了。tar -xvf 20151022164024.tar.gz 成功解压,解压后的路径是在backup_test中再次生成了source全路径。

Version1.1

改进处:把单纯的日期命名改成了年月日为文件夹,时间为文件名称。

today=target+time.strftime('%Y%m%s')
now=time.strftime('%H%M%S')
if not os.path.exists(today):
    os.mkdir(today)
    print 'Successfully created directory',today
target=today+os.sep+now+'.tar.gz'
结果:Successful backup to /opt/soft/backup_test/20151022/171053.tar.gz

Version1.2

 改进出:为压缩包增加描述

comment=raw_input('Enter a comment-->')
if len(comment)==0:
        target=today+os.sep+now+'.tar.gz'
else:
        target=today+os.sep+now+'_'+comment.replace(' ','_')+'.tar.gz'#多个单词的描述用空格隔开,替换为"_"
结果:Enter a comment-->add
Successful backup to /opt/soft/backup_test/20151023/112738_add.tar.gz
原文地址:https://www.cnblogs.com/zhaoxd07/p/4902430.html