例题P101

  1. python中r的用法,r'str'表示raw string,既忽略转义字符。因为和windows不一样,python中认为就是转义字符escape sequences的标志。
  2. python中提取系统时间,以及将其转化成字符串的方法。time.strftime()。
  3. 将list转化成str的方法,s.join(list),其中s是list不同元素转换成string后中间的空格符。
  4. 7z压缩的方法中 如果加上-t7z 这种方法的压缩效果更好
  5. 解决zip_command不能调用7z的两种办法:

a. 通过计算机→属性→系统保护→高级→环境变量→系统变量  path 修改环境变量,添加7z的path

b. 直接在zip_command命令中添加7z的路径,但是需要注意由于Program Files有空格,Python不能识别它,所以需要将zip_command改成:

    zip_command = r'D:Progra~17-Zip7z' + " a %s %s" % ( target, ' '.join(source) )

    造成这种原因是,dos下只支持8.3文件名规格,多过的都会以~1结尾

   

完成的小脚本是实现系统文件的备份。

#!F:/document/python
# Filename: backup_ver1.py
import os
import time
##import sys
##
##os.sys.path.append(r'D:Progra~17-Zip')
#1. the files and derectories to be backed up are specified in a list.
source = [r'f:documentpythona.txt',r'f:documenthtml']
#2. the backup must be stored in a main backup directory.
target_dir = r'f:documentackup\'
#3. the files are backed up into a zip file.
#4. the name of the zip archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
#5. put files in a zip archive
##zip_command = "rar a -r %s %s" % ( target, ' '.join(source) )
##zip_command = r'D:Progra~17-Zip7z' + " a %s %s" % ( target, ' '.join(source) )
zip_command = "7z a %s %s" % ( target, ' '.join(source) )
#  run the backup
if os.system(zip_command) == 0:
    print 'Successful backup to', target
else:
    print 'backup failed'

原文地址:https://www.cnblogs.com/linzh104/p/4096941.html