一、需求
如果我有一个压缩包需要解压,使用python可以自动化解压,最后又遇到如果解决的含有中文会乱码,需要根据情况把文件名还原。
二、不多说,直接上代码:
1、解决一个压缩包的代码:
import zipfile
import os
from pathlib import Path
def unzip_file(file_zip_path):
new_zip_dir = file_zip_path.rsplit('/',1)[0] + '/data'
if not os.path.isdir(new_zip_dir):
os.makedirs(new_zip_dir)
zFile = zipfile.ZipFile(file_zip_path, "r")
# ZipFile.namelist(): 获取ZIP文档内所有文件的名称列表
for fileM in zFile.namelist():
# zFile.extract(fileM, new_zip_dir)
# 解压出来单个文件
extracted_path = Path(zFile.extract(fileM,new_zip_dir))
# print("fileM.encode('cp437').decode('gbk')",fileM.encode('cp437').decode('gbk'))
# print("extracted_path",extracted_path)
# 文件重命名,将中文的文件名还原
extracted_path.rename(new_zip_dir+'//'+fileM.encode('cp437').decode('gbk'))
zFile.close()
return new_zip_dir
2、自动化下载一个压缩包并解压:
这个是增加了一个自动化下载压缩包,然后解压自己固定的目录,我这里制定目录。根据需求自行修改。
import requests
import zipfile
import os
from pathlib import Path
path = __file__
def down_load_zip(url):
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"
}
resp = requests.get(url, headers=headers)
content = resp.content
file_zip_path = '{}/data.zip'.format(path.rsplit('/',1)[0])
with open(file_zip_path, 'wb') as file_zip:
file_zip.write(content)
return file_zip_path
def unzip_file(file_zip_path):
new_zip_dir = file_zip_path.rsplit('/',1)[0] + '/data'
if not os.path.isdir(new_zip_dir):
os.makedirs(new_zip_dir)
zFile = zipfile.ZipFile(file_zip_path, "r")
# ZipFile.namelist(): 获取ZIP文档内所有文件的名称列表
for fileM in zFile.namelist():
# zFile.extract(fileM, new_zip_dir)
# 解压出来单个文件
extracted_path = Path(zFile.extract(fileM,new_zip_dir))
# print("fileM.encode('cp437').decode('gbk')",fileM.encode('cp437').decode('gbk'))
# print("extracted_path",extracted_path)
# 文件重命名,将中文的文件名还原
extracted_path.rename(new_zip_dir+'//'+fileM.encode('cp437').decode('gbk'))
zFile.close()
return new_zip_dir
if __name__ == '__main__':
zip_url = 'http://amr.gd.gov.cn/attachment/0/400/400270/3074870.zip'
file_zip_path = down_load_zip(zip_url)
print("file_zip_path",file_zip_path)
new_zip_dir = unzip_file(file_zip_path)
print("new_zip_dir",new_zip_dir)