python 解壓、復(fù)制、刪除 文件的實(shí)例代碼
壓縮復(fù)制刪除文件基于python語言怎么操作呢,壓縮文件有四種格式:zip、rar、tar、tar.gz,在壓縮過程中也容易出現(xiàn)很多問題,今天小編通過代碼給大家詳解,具體內(nèi)容如下所示:
一、python3解壓文件
1.python 解壓文件代碼示例
如下代碼主要實(shí)現(xiàn)zip、rar、tar、tar.gz四種格式的壓縮文件的解壓
def unzip_file(src_file, dst_dir=None, unzipped_files=None, del_flag=True):
"""
根據(jù)指定的壓縮文件類型遞歸解壓所有指定類型的壓縮文件
:param src_file: 解壓的源文件路徑,可以為文件夾路徑也可以是文件路徑
:param dst_dir: 解壓后的文件存儲(chǔ)路徑
:param unzipped_files: 完成解壓的文件名列表
:param del_flag: 解壓完成后是否刪除原壓縮文件,默認(rèn)刪除
:return: 完成解壓的文件名列表
"""
# 完成解壓的文件名列表初始為空
if unzipped_files is None:
unzipped_files = []
# 指定的解壓文件類型
zip_types = ['.zip', '.rar', '.tar', '.gz']
def exec_decompress(zip_file, dst_dir):
"""
解壓實(shí)現(xiàn)的公共代碼
:param zip_file: 壓縮文件全路徑
:param dst_dir: 解壓后文件存儲(chǔ)路徑
:return:
"""
file_suffix = os.path.splitext(zip_file)[1].lower()
try:
print('Start extracting the file: %s' % zip_file)
# zip 解壓
if file_suffix == '.zip':
# zip解壓 寫法一
with ZipFile(zip_file, mode='r') as zf:
zf.extractall(dst_dir)
# zip解壓 寫法二
# file_zip = ZipFile(zip_file, mode='r')
# for file in file_zip.namelist():
# file_zip.extract(file, dst_dir)
# file_zip.close()
# rar 解壓
elif file_suffix == '.rar':
rf = rarfile.RarFile(zip_file)
rf.extractall(dst_dir)
# tar、tgz(tar.gz) 解壓
elif file_suffix in ['.tar', '.gz']:
tf = tarfile.open(zip_file)
tf.extractall(dst_dir)
# 關(guān)閉文件釋放內(nèi)存
tf.close()
print('Finished extracting the file: %s' % zip_file)
except Exception as e:
print(e)
# 解壓完成加入完成列表
unzipped_files.append(zip_file)
# 根據(jù)標(biāo)識(shí)執(zhí)行原壓縮文件刪除
if del_flag and os.path.exists(zip_file):
os.remove(zip_file)
# 如果傳入的文件路徑為文件目錄,則遍歷目錄下所有文件
if os.path.isdir(src_file):
# 初始化文件目錄下存在的壓縮文件集合為空
zip_files = []
# 如果傳入的目的文件路徑為空,則取解壓的原文件夾路徑
dst_dir = dst_dir if dst_dir else src_file
# 遍歷目錄下所有文件
for file in os.listdir(src_file):
file_path = os.path.join(src_file, file)
# 如果是文件夾則繼續(xù)遞歸解壓
if os.path.isdir(file_path):
dst_path = os.path.join(dst_dir, file)
unzip_file(file_path, dst_path, unzipped_files)
# 如果是指定類型的壓縮文件則加入到壓縮文件列表
elif os.path.isfile(file_path) and os.path.splitext(file_path)[
1].lower() in zip_types and file_path not in unzipped_files:
zip_files.append(file_path)
# 遍歷壓縮文件列表,執(zhí)行壓縮文件的解壓
for zip_file in zip_files:
exec_decompress(zip_file, dst_dir)
# 如果當(dāng)前目錄存在壓縮文件則完成所有文件解壓后繼續(xù)遍歷
if zip_files:
unzip_file(dst_dir, unzipped_files=unzipped_files)
# 如果傳入的文件路徑是指定類型的壓縮文件則直接執(zhí)行解壓
elif os.path.isfile(src_file) and os.path.splitext(src_file)[1].lower() in zip_types:
dst_dir = dst_dir if dst_dir else os.path.dirname(src_file)
exec_decompress(src_file, dst_dir)
return unzipped_files
2.python解壓常見問題解決辦法
2.1 python3 zipfile解壓文件名亂碼解決辦法
直接修改源碼,即 zipfile.py 文件:
第一處:
if flags & 0x800:
# UTF-8 file names extension
filename = filename.decode('utf-8')
else:
# Historical ZIP filename encoding
# 注釋原代碼
# filename = filename.decode('cp437')
# 新加一行代碼
filename = filename.decode('gbk')
第二處:
if zinfo.flag_bits & 0x800:
# UTF-8 filename
fname_str = fname.decode("utf-8")
else:
# 注釋原代碼
# fname_str = fname.decode("cp437")
# 同樣新加一行代碼
fname_str = fname.decode('gbk')
2.1 rar 解壓無法找到動(dòng)態(tài)庫(unrar.dll)解決辦法
報(bào)錯(cuò)示例:

第一步 手動(dòng)下載動(dòng)態(tài)庫文件 unrar.dll 存在本地目錄,例如我的本地存儲(chǔ)路徑為:C:\MySoft\assist\unrar.dll
鏈接: https://pan.baidu.com/s/1rqhFND9XmtD1Y8yGLEz9kA 提取碼: u2my
第二步 修改源碼 unrarlib.py 文件
if platform.system() == 'Windows':
from ctypes.wintypes import HANDLE as WIN_HANDLE
HANDLE = WIN_HANDLE
UNRARCALLBACK = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_uint,
ctypes.c_long, ctypes.c_long,
ctypes.c_long)
# 注釋原代碼
# lib_path = lib_path or find_library("unrar.dll")
# 將路徑指向下載的動(dòng)態(tài)庫文件存儲(chǔ)路徑
lib_path = r"C:\MySoft\assist\unrar.dll"
if lib_path:
unrarlib = ctypes.WinDLL(lib_path)
知識(shí)點(diǎn)擴(kuò)展:python 壓縮文件夾的代碼
def zip_ya(start_dir):
start_dir = start_dir # 要壓縮的文件夾路徑
file_news = start_dir + '.zip' # 壓縮后文件夾的名字
z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
for dir_path, dir_names, file_names in os.walk(start_dir):
f_path = dir_path.replace(start_dir, '') # 這一句很重要,不replace的話,就從根目錄開始復(fù)制
f_path = f_path and f_path + os.sep or '' # 實(shí)現(xiàn)當(dāng)前文件夾以及包含的所有文件的壓縮
for filename in file_names:
z.write(os.path.join(dir_path, filename), f_path + filename)
z.close()
return file_news
PS: 若遞歸掃描所有文件夾過程中有文件夾里不存在文件, 該文件夾將被忽略
總結(jié)
到此這篇關(guān)于python 解壓、復(fù)制、刪除 文件的實(shí)例代碼的文章就介紹到這了,更多相關(guān)python 解壓、復(fù)制、刪除 文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python通用讀取vcf文件的類(復(fù)制粘貼即可用)
- 復(fù)制粘貼功能的Python程序
- Python列表的深復(fù)制和淺復(fù)制示例詳解
- Python文件名匹配與文件復(fù)制的實(shí)現(xiàn)
- 基于python實(shí)現(xiàn)復(fù)制文件并重命名
- python利用os模塊編寫文件復(fù)制功能——copy()函數(shù)用法
- python實(shí)現(xiàn)跨excel sheet復(fù)制代碼實(shí)例
- python pptx復(fù)制指定頁的ppt教程
- python如何實(shí)現(xiàn)復(fù)制目錄到指定目錄
- linux 下python多線程遞歸復(fù)制文件夾及文件夾中的文件
- 如何用python實(shí)現(xiàn)復(fù)制粘貼功能
相關(guān)文章
基于python list對(duì)象中嵌套元組使用sort時(shí)的排序方法
下面小編就為大家分享一篇基于python list對(duì)象中嵌套元組使用sort時(shí)的排序方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04
python使用PyV8執(zhí)行javascript代碼示例分享
這篇文章主要介紹了python使用PyV8執(zhí)行javascript的小示例,大家參考使用吧2013-12-12
使用IPython或Spyder將省略號(hào)表示的內(nèi)容完整輸出
這篇文章主要介紹了使用IPython或Spyder將省略號(hào)表示的內(nèi)容完整輸出,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04
python入門基礎(chǔ)之用戶輸入與模塊初認(rèn)識(shí)
Python的強(qiáng)大之處在于他有非常豐富和強(qiáng)大的標(biāo)準(zhǔn)庫和第三方庫,幾乎你想實(shí)現(xiàn)的任何功能都有相應(yīng)的Python庫支持。下面通過本文給大家介紹python入門基礎(chǔ)之用戶輸入與模塊初認(rèn)識(shí),一起看看吧2016-11-11
python爬蟲 基于requests模塊的get請(qǐng)求實(shí)現(xiàn)詳解
這篇文章主要介紹了python爬蟲 基于requests模塊的get請(qǐng)求實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08

