今天写项目遇到了上传压缩文件获取json文件的需求,问了度娘,加上自己的一些理解,贴出以下代码(已验证),供以后查阅
import json
import zipfile
import os
class zip:
@staticmethod
def delete_zip(zip_name):
try:
os.remove(zip_name)
except Exception as e:
print(e)
@staticmethod
def unzip(zip_name, dir_path):
"""
解压目标文件并且删除源文件
:param zip_name: 压缩文件路径
:param dir_path: 解压目录路径
:return:
"""
try:
with zipfile.ZipFile(zip_name, 'r') as f:
f.extractall(dir_path)
zip.delete_zip(zip_name) # 删除zip
zip.recode(dir_path) # 对文件名重新编码
except Exception as e:
print(e)
@staticmethod
def read_config(dir_path):
"""
读取配置文件
:param dir_path:服务目录路径
:return:json格式的数据
"""
try:
with open(os.path.join(dir_path, 'config.json'), encoding="gbk") as f:
# 注意编码问题
setting = json.load(f)
return setting
except Exception as e:
print(e)
@staticmethod
def recode(dir_path):
"""
对解压的文件重新编码,解决乱码问题
:param dir_path: 解压目录路径
:return:
"""
for root_path, dir_names, file_names in os.walk(dir_path):
for fn in file_names:
# 具体看os.walk()文档
path = os.path.join(root_path, fn)
if not zipfile.is_zipfile(path):
try:
fn = fn.encode('cp437').decode('gbk')
new_path = os.path.join(root_path, fn)
os.rename(path, new_path)
except Exception as e:
print('error:', e)