Python3.2 实现zip压缩与解压缩功能
2011-04-23 14:21
671 查看
刚接触Python,用Python3试着写了一个Zip文件的压缩和解压缩脚本,不足之处,欢迎拍砖
功能有限,要按照脚本压缩文件或者文件夹,必须进入文件所在目录,以文件所在目录为工作路径,并且默认压缩后的文件名同于原文件所在的目录名、解压后的文件夹名同于解压前的文件名
压缩功能分为压缩所在目录的所有文件跟部分文件(部分文件需要手动添加文件名);解压功能分为解压到当前目录跟解压到指定目录,以下为代码:
功能有限,要按照脚本压缩文件或者文件夹,必须进入文件所在目录,以文件所在目录为工作路径,并且默认压缩后的文件名同于原文件所在的目录名、解压后的文件夹名同于解压前的文件名
压缩功能分为压缩所在目录的所有文件跟部分文件(部分文件需要手动添加文件名);解压功能分为解压到当前目录跟解压到指定目录,以下为代码:
]#!/usr/bin/env python3 import os,zipfile def Zip(target_dir): target_file=os.path.basename(os.getcwd())+'.zip' zip_opt=input("Will you zip all the files in this dir?(Choose 'n' you should add files by hand)y/n: ") while True: if zip_opt=='y': #compress all the files in this dir filenames=os.listdir(os.getcwd()) #get the file-list of this dir zipfiles=zipfile.ZipFile(os.path.join(target_dir,target_file),'w',compression=zipfile.ZIP_DEFLATED) for files in filenames: zipfiles.write(files) zipfiles.close() print("Zip finished!") break elif zip_opt=='n': #compress part of files of this dir filenames=list(input("Please input the files' name you wanna zip:")) zipfiles=zipfile.ZipFile(os.path.join(target_dir,target_file),'w',compression=zipfile.ZIP_DEFLATED) for files in filenames: zipfiles.write(files) zipfiles.close() print("Zip finished!") break else: print("Please in put the character 'y' or 'n'") zip_opt=input("Will you zip all the files in this dir?(Choose 'n' you should add files by hand)y/n: ") def Unzip(target_dir): target_name=input("Please input the file you wanna unzip:") zipfiles=zipfile.ZipFile(target_name,'r') zipfiles.extractall(os.path.join(target_dir,os.path.splitext(target_name)[0])) zipfiles.close() print("Unzip finished!") def main(): opt=input("What are you gonna do?Zip choose 'y',unzip choose 'n'.y/n: ") while True: if opt=='y': #compress files zip_dir=input("Please input the absdir you wanna put the zip file in:") Zip(zip_dir) break elif opt=='n': #unzip files unzip_dir=input("Please input the absdir you wanna put the zip file in(Nothing should be done if you wann unzip files in the current dir):") if unzip_dir=='': Unzip(os.getcwd()) else: Unzip(unzip_dir) break else: print("Please input the character 'y' or 'n'") opt=input("What are you gonna do?Zip choose 'y',unzip choose 'n'.y/n: ") if __name__=='__main__': main()
相关文章推荐
- Python压缩解压缩zip文件及破解zip文件密码的方法
- 三个利用Java实现zip压缩/解压缩方法
- C#+ICSharpCode.SharpZipLib.dll实现压缩解压缩功能
- php实现zip压缩文件解压缩代码分享(简单易懂)
- 三个利用Java实现zip压缩/解压缩方法
- 利用Java实现压缩与解压缩(zip、gzip)支持中文路径
- python zipfile压缩解压缩目录
- Android 利用Java实现压缩与解压缩(zip、gzip)支持中文路径
- 利用Java实现压缩与解压缩(zip、gzip)支持中文路径
- java实现简单压缩与解压缩功能
- 【转】python的zipfile压缩、解压缩
- python的zipfile实现文件目录解压缩
- Python压缩解压缩zip文件及破解zip文件密码的方法
- 在.NET应用程序中使用7-Zip的压缩/解压缩功能
- 利用Java实现压缩与解压缩(zip、gzip)支持中文路径
- php实现zip压缩文件解压缩代码分享(简单易懂)
- java实现单个或多个文件的压缩、解压缩 支持zip、rar等格式
- 使用ant实现zip压缩和解压缩(一)
- 利用Java实现压缩与解压缩(zip、gzip)支持中文路径
- 利用Java实现压缩与解压缩(zip、gzip)支持中文路径