經常由于各種壓縮格式的不一樣用到檔案的解壓縮時就需要下載不同的解壓縮工具去處理不同的檔案,以至于桌面上的壓縮工具就有三四種,于是使用python做了一個包含各種常見格式的檔案解壓縮的小工具,

閱讀全文
常見的壓縮格式主要是下面的四種格式:
zip 格式的壓縮檔案,一般使用360壓縮軟體進行解壓縮,
tar.gz 格式的壓縮檔案,一般是在linux系統上面使用tar命令進行解壓縮,
rar 格式的壓縮檔案,一般使用rar壓縮軟體進行解壓縮,
7z 格式的壓縮檔案,一般使用7-zip壓縮軟體進行解壓縮,
匯入zip格式的解壓縮處理的非標準庫,
import os
import zipfile as zip
撰寫zip解壓縮格式的檔案壓縮函式,
def do_zip(source_, target_file):
'''
zip檔案壓縮
:param source_: 原始檔案路徑
:param target_file: 目標檔案路徑
:return:
'''
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解壓縮格式的檔案解壓縮函式,
def un_zip(source_file, target_):
'''
zip檔案解壓縮
:param source_file: 原始檔案路徑
:param target_: 目標檔案路徑
:return:
'''
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格式的解壓縮處理的非標準庫,
import py7zr
撰寫7z解壓縮格式的檔案壓縮函式,
def do_7z(source_, target_file):
'''
7z檔案壓縮
:param source_:
:param target_file:
:return:
'''
with py7zr.SevenZipFile(target_file, 'r') as file:
file.extractall(path=source_)
撰寫7z解壓縮格式的檔案解壓縮函式,
def un_7z(source_file, target_):
'''
7z檔案解壓縮
:param source_file:
:param target_:
:return:
'''
with py7zr.SevenZipFile(source_file, 'w') as file:
file.writeall(target_)
匯入rar格式的解壓縮處理的非標準庫,
import rarfile as rar
撰寫rar解壓縮格式的檔案解壓縮函式,
def un_rar(source_file, target_):
'''
rar檔案解壓縮
:param source_file: 原始檔案
:param target_: 目標檔案路徑
:return:
'''
obj_ = rar.RarFile(source_file.decode('utf-8'))
obj_.extractall(target_.decode('utf-8'))
接下來開始進入正題了,首先使用print函式列印一下選單選項,可以讓用戶在啟動軟體后進行選單的選擇,
print('==========PYTHON工具:檔案解壓縮軟體==========')
print('說明:目前支持zip、7z、rar格式')
print('1、檔案解壓縮格式:zip/rar/7z')
print('2、檔案操作型別(壓縮/解壓):Y/N')
print('3、檔案路徑選擇,需要輸入相應的操作檔案路徑')
print('==========PYTHON工具:檔案解壓縮軟體==========')
使用input函式接收用戶輸入的檔案解壓縮格式,
format_ = input('請輸入檔案解壓縮的格式:\n')
使用input函式接收用戶輸入的檔案操作型別(壓縮/解壓),
type_ = input('請輸入檔案操作的型別:\n')
使用input函式接收用戶輸入的需要操作的檔案路徑,
source_ = input('請輸入原始檔案的存盤路徑(檔案或目錄):\n')
使用input函式接收用戶輸入的生成的新檔案的目標路徑,
target_ = input('請輸入目標檔案的存盤路徑(檔案或目錄):\n')
為了保持輸入的靈活性,加入不同格式不同操作型別的業務判斷,
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中最簡單的turtle繪圖:奧運五環!
知識匯總:python辦公自動化應該學習哪些內容?
python多執行緒同步售票系統解決思路...
發現幾個好玩的游戲編程平臺,與君共勉!
python四個性能檢測工具,包括函式的運行記憶體、時間等等...
歡迎關注作者公眾號【Python 集中營】,專注于后端編程,每天更新技術干貨,不定時分享各類資料!轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/472869.html
標籤:Python
