Problem: Write a program that can create backups for all important files
consider: what the source and destination paths are, what all important files are, what the backup file format is, how backup file names are defined, and so on. (PS, I only think of a path and name)
Programming:
1 files and directories that need to be backed up are specified by a list
2 backups should be saved in the primary backup directory.
3 files back into a tar file (the original document is a ZIP file, my Linux is not installed, so use tar)
4 The name of the TAR archive is the current date and time
5 using the Standard tar command
Version1.0
#/usr/bin/python#Filename:backup_ver1.py#-*-coding:utf-8-*-ImportOSImport Time#1 The files and directories to is backed up is specified in a list.source=['/home/zhaoxiaodan/pythontest/*','/home/zhaoxiaodan/javatest']#2 The backup must is stored in a main backup directoryTarget_dir='/opt/soft/backup_test/'#3 The backup file is tar.gz, and named with dateTarget=target_dir+time.strftime ('%y%m%d%h%m%s')+'. tar.gz'#4 Use the tar.gz commandTar_command="tar cvf%s%s"% (target,' '. Join (source))ifOs.system (tar_command) = =0:Print 'successful backup to%s'%TargetElse: Print 'Failed‘
Results: Successful backup to/opt/soft/backup_test/20151022171749.tar.gz
when unpacking the compressed package, there are the following problem :
[[Email protected]xbackup_test]# tar-xzvf 201510221640241tar:error is not recoverable:exiting now
Check that the compression package is not compressed in gzip format, so when the decompression is not added Z. Direct TAR-XF on it. TAR-XVF 20151022164024.tar.gz successfully decompression, the path after decompression is in Backup_test again generated the source full path.
Version1.1
Improvement: The simple date name changed to the month and day for the folder, the time is the file name.
today=target+time.strftime ( " %y%m%s " ) now =time.strftime ( ' %h%m%s ' ) not Os.path.exists (today): Os.mkdir (today) print successfully created directory ,todaytarget =today+os.sep+now+ .tar.gz Result: Successful backup to/opt/soft/backup_test/20151022/171053. tar.gz
Version1.2
Improved: Add a description for a compressed package
Comment=raw_input ('Enter a comment-->')ifLen (comment) = =0:target=today+os.sep+now+'. tar.gz'Else: Target=today+os.sep+now+'_'+comment.replace (' ','_')+'. tar.gz' #多个单词的描述用空格隔开, replaced by ' _ '
Result: Enter a Comment-->add
Successful backup to/opt/soft/backup_test/20151023/112738_add.tar.gz
A Python instance: Create a backup of important files. Excerpt from Crossin-python's Concise tutorial