简明 Python 教程 -- 第10章 解决问题——编写一个Python脚本
2007-03-29 11:52:03 来源:WEB开发网核心提示: 输出$ python backup_ver2.pySuccessfully created directory /mnt/e/backup/20041208Successful backup to /mnt/e/backup/20041208/080020.zip$ python back
输出
$ python backup_ver2.py
Successfully created directory /mnt/e/backup/20041208
Successful backup to /mnt/e/backup/20041208/080020.zip
$ python backup_ver2.py
Successful backup to /mnt/e/backup/20041208/080428.zip
它如何工作
两个程序的大部分是相同的。改变的部分主要是使用os.exists函数检验在主备份目录中是否有以当前日期作为名称的目录。如果没有,我们使用os.mkdir函数创建。
注意os.sep变量的用法——这会根据你的操作系统给出目录分隔符,即在Linux、Unix下它是'/',在Windows下它是'\',而在Mac OS下它是':'。使用os.sep而非直接使用字符,会使我们的程序具有移植性,可以在上述这些系统下工作。
版本三
第二个版本在我做较多备份的时候还工作得不错,但是如果有极多备份的时候,我发现要区分每个备份是干什么的,会变得十分困难!例如,我可能对程序或者演讲稿做了一些重要的改变,于是我想要把这些改变与zip归档的名称联系起来。这可以通过在zip归档名上附带一个用户提供的注释来方便地实现。
例10.3 备份脚本——版本三(不工作!)
#!/usr/bin/python
# Filename: backup_ver3.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:Documents', r'D:Work'] or something like that
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the zip file
comment = raw_input('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' +
comment.replace(' ', '_') + '.zip'
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
(源文件:code/backup_ver3.py)
更多精彩
赞助商链接