(初学者)关于Python学习中Windows环境中遇到的info-zip问题的解决

来源:互联网 发布:瓦楞纸箱设计软件 编辑:程序博客网 时间:2024/05/22 09:45

(初学者)关于Python学习中Windows环境中遇到的info-zip问题的解决

最近在自学python,教材看的是《简明Python教程》A Byte of Python网址:http://www.kuqin.com/abyteofpython_cn/index.html
在第十章10.1版本一的代码中有使用zip的command line进行文件夹的压缩操作,代码如下(根据Windows系统稍作修改):

#!D:/Python#Filename:backup_ver1.pyimport osimport time#1.The files and directories to be backed up are specified in a list.source = [r'E:\test1',r'E:\test2']#If you are using Linux,use source = #['/home/swaroop/byte','/home/swaroop/bin'] or something like that#2.The backup must be stored in a main backup dirctorytarget_dir = 'E:\\target\\'#Remember to change this to what you will be using#3.The files are backed up into a zip file.#4.The name of the zip archive is the current data and timetarget = target_dir + time.strftime('%Y%m%d%H%M%S')+'.zip'#5.We use the zip command(in Unix/Linux)to put the file in a zip archivezip_command = "zip -qr '%s'%s"%(target,' '.join(source))print(zip_command)#Run the backupif os.system(zip_command)==0:    print('Successful backup to',target)else:    print('Backup FAILED')

注意到此代码中zip命令为Linux发行版提供,由于我的编译环境是在Windows10的环境中开发的,故需要zip command line的windows版本。教材中作者提到可以使用info-Zip进行替换。网上搜了一下,找到了这个:http://www.info-zip.org/Zip.html

点击Downloads后点击页面中的链接:Info-ZIP’s SourceForge site

到SourceForge中下载得到WiZ503xN.exe,运行extract后发现该exe并不支持command line(可设置环境变量后输入WIZ检验)。故此info-zip不可用.后来又搜索了各种WinZip、7-Zip等都不太理想。后来终于找到这个网站:http://stahlworks.com/dev/index.php?tool=zipunzip
点击页面中的zip.exe here下载zip.exe后设置Path环境变量后输入zip出现如下窗口:

表明正确添加了zip命令行。
此时再运行开头处的代码,发现已经可以运行zip命令。但是在运行zip_command = “zip -qr ‘%s’ %s” % (target, ’ ‘.join(source))时出错,在网上找到的方法,将此句中’%s’的”去掉。
另外注意(target, ’ ‘.join(source))中”中的空格,只有加入了空格zip才能识别多个文件夹。
最终代码如下:

#!D:/Python#Filename:backup_ver1.pyimport osimport time#1.The files and directories to be backed up are specified in a list.source = [r'E:\test1',r'E:\test2']#If you are using Linux,use source = #['/home/swaroop/byte','/home/swaroop/bin'] or something like that#2.The backup must be stored in a main backup dirctorytarget_dir = 'E:\\target\\'#Remember to change this to what you will be using#3.The files are backed up into a zip file.#4.The name of the zip archive is the current data and timetarget = target_dir + time.strftime('%Y%m%d%H%M%S')+'.zip'#5.We use the zip command(in Unix/Linux)to put the file in a zip archivezip_command = "zip -qr %s %s"%(target,' '.join(source))print(zip_command)#Run the backupif os.system(zip_command)==0:    print('Successful backup to',target)else:    print('Backup FAILED')

按F5运行后提示运行成功!