经常由于各种压缩格式的不一样用到文件的解压缩时就需要下载不同的解压缩工具去处理不同的文件,以至于桌面上的压缩工具就有三四种,于是使用python做了一个包含各种常见格式的文件解压缩的小工具。
常见的压缩格式主要是下面的四种格式:
zip 格式的压缩文件,一般使用360压缩软件进行解压缩。
tar.gz 格式的压缩文件,一般是在linux系统上面使用tar命令进行解压缩。
rar 格式的压缩文件,一般使用rar压缩软件进行解压缩。
7z 格式的压缩文件,一般使用7-zip压缩软件进行解压缩。
导入zip格式的解压缩处理的非标准库。
1 2 | import os
import zipfile as zip
|
编写zip解压缩格式的文件压缩函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def do_zip(source_, target_file):
zip_file = zip .ZipFile(target_file, 'w' )
pre_len = len (os.path.dirname(source_))
for parent, dirnames, filenames in os.walk(source_):
for filename in filenames:
print (f '{filename}' )
path_file = os.path.join(parent, filename)
arcname = path_file[pre_len:].strip(os.path.sep)
zip_file.write(path_file, arcname)
zip_file.close()
|
编写zip解压缩格式的文件解压缩函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | def un_zip(source_file, target_):
zip_file = zip .ZipFile(source_file)
if os.path.isdir(target_):
pass
else :
os.mkdir(target_)
for names in zip_file.namelist():
zip_file.extract(names, target_)
zip_file.close()
|
导入7z格式的解压缩处理的非标准库。
编写7z解压缩格式的文件压缩函数。
1 2 3 4 5 6 7 8 9 | def do_7z(source_, target_file):
with py7zr.SevenZipFile(target_file, 'r' ) as file :
file .extractall(path = source_)
|
编写7z解压缩格式的文件解压缩函数。
1 2 3 4 5 6 7 8 9 | def un_7z(source_file, target_):
with py7zr.SevenZipFile(source_file, 'w' ) as file :
file .writeall(target_)
|
导入rar格式的解压缩处理的非标准库。
编写rar解压缩格式的文件解压缩函数。
1 2 3 4 5 6 7 8 9 | def un_rar(source_file, target_):
obj_ = rar.RarFile(source_file.decode( 'utf-8' ))
obj_.extractall(target_.decode( 'utf-8' ))
|
接下来开始进入正题了,首先使用print函数打印一下菜单选项,可以让用户在启动软件后进行菜单的选择。
1 2 3 4 5 6 | print ( '==========PYTHON工具:文件解压缩软件==========' )
print ( '说明:目前支持zip、7z、rar格式' )
print ( '1、文件解压缩格式:zip/rar/7z' )
print ( '2、文件操作类型(压缩/解压):Y/N' )
print ( '3、文件路径选择,需要输入相应的操作文件路径' )
print ( '==========PYTHON工具:文件解压缩软件==========' )
|
使用input函数接收用户输入的文件解压缩格式。
1 | format_ = input ( '请输入文件解压缩的格式:\n' )
|
使用input函数接收用户输入的文件操作类型(压缩/解压)。
1 | type_ = input ( '请输入文件操作的类型:\n' )
|
使用input函数接收用户输入的需要操作的文件路径。
1 | source_ = input ( '请输入原始文件的存储路径(文件或目录):\n' )
|
使用input函数接收用户输入的生成的新文件的目标路径。
1 | target_ = input ( '请输入目标文件的存储路径(文件或目录):\n' )
|
为了保持输入的灵活性,加入不同格式不同操作类型的业务判断。
1 2 3 4 5 6 7 8 9 10 11 12 | if format_ = = 'zip' and type_ = = 'Y' :
do_zip(source_, target_)
elif format_ = = 'zip' and type_ = = 'N' :
un_zip(source_, target_)
elif format_ = = 'rar' and type_ = = 'Y' :
un_zip(source_, target_)
elif format_ = = 'rar' and type_ = = 'N' :
un_zip(source_, target_)
elif format_ = = '7z' and type_ = = 'Y' :
un_zip(source_, target_)
elif format_ = = '7z' and type_ = = 'N' :
un_zip(source_, target_)
|
目前功能点是做了三种格式,后期若是需要可能会扩展升级当前的版本。
以上就是基于Python怎么制作一个文件解压缩工具的详细内容
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。