网上要么没有,要么方法都是不对的。
直接上代码,应该注释挺清楚了,不多说了^_^
import os
import sys
import zipfile
#获取脚本路径, 如果是在IDE下运行,只能用此方式获取
def get_cur_dir():
path = sys.path[0]
#判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是py2exe编译后的文件,则返回的是编译后的文件路径
if os.path.isdir(path):
return path
elif os.path.isfile(path):
return os.path.dirname(path)
def recurse_files(input_path, result):
files = os.listdir(input_path)
for file in files:
if os.path.isdir(os.path.join(input_path,file)):
if file != 'users': #过滤文件夹
recurse_files(os.path.join(input_path,file), result)
else:
ext = os.path.splitext(file)[1]
if input_path == cur_dir:#根目录只添加特定类型文件
if ext == '.dll' or ext == '.exe' or ext == '.qm':
result.append(os.path.join(input_path,file))
else:
result.append(os.path.join(input_path,file))
if __name__ == '__main__':
cur_dir = get_cur_dir()
zip_file_name = os.path.join(cur_dir, 'debug.zip');
if os.path.isfile(zip_file_name): os.remove(zip_file_name)
zip = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED)
filelists = []
recurse_files(cur_dir, filelists)
for file in filelists:
arcName = file #在压缩包内名字
if os.path.dirname(file) == cur_dir:
arcName = os.path.basename(file) #文件在要压缩目录下,则只为文件名
else:
dir = os.path.dirname(file)
dir = dir.replace(cur_dir + '\\', '') #只从要压缩的目录下当前目录名开始
arcName = dir + '\\' + os.path.basename(file)
zip.write(file, arcName)
#zip.write(file) #会出现全路径
# 调用了close方法才会保证完成压缩
zip.close()
python打包压缩目录,支持子目录,支持过滤目录和文件类型,压缩包内路径从当前开始,而不是从盘符开始的长路径
最新推荐文章于 2024-09-25 21:28:05 发布
本文提供了一个使用Python进行文件批量压缩的实用代码示例。通过递归遍历指定目录下的所有文件,包括子目录,该脚本能够将符合特定条件的文件(如.dll,.exe,.qm等)压缩到一个ZIP文件中。代码详细展示了如何获取脚本路径,如何筛选并添加文件到压缩包,以及如何确保压缩操作完整执行。
3万+

被折叠的 条评论
为什么被折叠?



