文件解压源码如下:其中入参为zip包文件目录,出参为解压后文件夹目录,如输入 /tmp/1.zip,返回 /tmp/1/
import os
import zipfile
def unzip_resource(zip_path):
file_name = os.path.basename(zip_path)
file_dir = os.path.dirname(zip_path)
if os.path.splitext(zip_path)[1] == '.zip':
file_zip = zipfile.ZipFile(zip_path, 'r')
for resource_file in file_zip.namelist():
file_zip.extract(resource_file, file_dir + '/' + file_name.replace('.zip', ''))
file_path = zip_path.replace('.zip', '')
resource_path = file_path + '/'
return resource_path
文件夹打包源码如下:其中入参为文件夹名称以及压缩后文件的名字
import os
import zipfile
def abcZip(dir_path, file_name):
with zipfile.ZipFile(file_name, 'w', zipfile.ZIP_DEFLATED) as target:
for dirpath, dirnames, filenames in os.walk(dir_path):
fpath = dirpath.replace(dir_path, '')
fpath = fpath and fpath + os.sep or ''
for filename in filenames:
# file_list.append(os.path.join(dirpath,filename))
# print(os.path.join(dirpath,filename)
if (filename.__contains__('.DS_Store')):
continue
target.write(os.path.join(dirpath, filename), fpath + filename)
target.close()