xywuyiba6 发表于 2015-4-28 07:10:07

Python 初体验(四)

  学习语言最好的办法就是实践,这句话一点都不假!
  今天完成了一个Python的小脚本,但是其中却遇到了一些意想不到的困难,最终通过上网搜索资料终于将这些问题解决了,对于我这个连Python都还不是太懂的菜鸟来说,真的很不容易啊!
  学到了什么?

[*]python中r的用法,r'str'表示raw string,既忽略转义字符。因为和windows不一样,python中认为\就是转义字符escape sequences的标志。
[*]python中提取系统时间,以及将其转化成字符串的方法。time.strftime()。
[*]将list转化成str的方法,s.join(list),其中s是list不同元素转换成string后中间的空格符。
[*]7z压缩的方法中 如果加上-t7z 这种方法的压缩效果更好
[*]解决zip_command不能调用7z的两种办法:
  a. 通过计算机→属性→系统保护→高级→环境变量→系统变量path 修改环境变量,添加7z的path
  b. 直接在zip_command命令中添加7z的路径,但是需要注意由于Program Files有空格,Python不能识别它,所以需要将zip_command改成:
  zip_command = r'D:\Progra~1\7-Zip\7z' + " 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~1\7-Zip')
#1. the files and derectories to be backed up are specified in a list.
source =
#2. the backup must be stored in a main backup directory.
target_dir = r'f:\document\backup\\'
#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~1\7-Zip\7z' + " 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'
页: [1]
查看完整版本: Python 初体验(四)