把左侧当前目录下所有文件进行压缩,右侧为文件压缩后的结果。
要求:
1)所有文件都能压缩
2)压缩后的文件路径不能太深,如图右侧所示。
import time
import os
import zipfile
def get_zip_file(file_path, file_lists):
files = os.listdir(file_path)
for file in files:
if os.path.isdir(file_path + '/' + file):
get_zip_file(file_path + '/' + file, file_lists)
else:
file_lists.append(file_path + '/' + file)
def zip_file(file_path, output_path, output_name):
newzip = zipfile.ZipFile(output_path + '/' + output_name, 'w', zipfile.ZIP_DEFLATED)
file_lists = []
get_zip_file(file_path, file_lists)
for file in file_lists:
full_file_path = file
compressed_file_path = file.split(file_path)[1]
# be care full about these two parameters: full_file_path, compressed_file_path
# as their names show.
newzip.write(full_file_path, compressed_file_path)
newzip.close()
return output_name
[1] https://blog.csdn.net/dou_being/article/details/81546172
解决了能够压缩所有文件的问题,但是路径太深。
[2] https://blog.csdn.net/sun_wangdong/article/details/79157682?utm_source=blogxgwz3
解决了压缩路径不深的问题,但是被压缩的文件层级比较多,这个问题没有解决。