使用Python调用7-Zip【按大小分组】压缩文件夹中所有文件
- 问题描述:
- 方法
- 前提条件
- 任务
- 完整代码示例
- 代码如何工作?
问题描述:
我现在想把文件夹下的所有内容上传到网盘,但是这个文件夹下的素材内容很多,使用分卷压缩的话,要一起压缩完上传。解压时得一起下载完再解压。200多G太大了。
又因为其实我用不完这个文件夹下全部的素材,有时候只下载一些就够用了,所以我希望:
能使用python
调用 7-zip
,每20G
压缩一个压缩包,命名后保存。直到把文件夹下所有的文件压缩完。
方法
前提条件
在动手之前,你需要准备以下工具:
- Python:推荐使用Python 3.x版本,已安装并可运行。
- 7-Zip:一个免费的压缩工具,点击这里下载并安装。
- 基本环境:确保你的电脑上Python和7-Zip都能正常运行。
任务
- 文件管理:将大文件夹拆分成小份,便于上传或存储。
- 自动化:通过Python脚本,避免手动操作的繁琐。
- 通用性:不仅限于视频文件,适用于任何类型文件。
完整代码示例
- `seven_zip_path`:替换为你的7zip的安装路径。
folder_path
:替换为你的文件夹路径。output_dir
:设置压缩包保存位置。max_size_gb
:调整每组的大小(比如10GB、50GB)。password
:输入你的压缩包密码,或者留空(password = None
)。
import os
import subprocess# 获取文件夹中的所有文件
def get_all_files(folder_path):"""遍历文件夹,返回所有文件的路径列表"""file_list = []for root, dirs, files in os.walk(folder_path):for file in files:file_path = os.path.join(root, file)file_list.append(file_path)return file_list# 按大小分组文件
def group_files_by_size(file_list, max_size_gb=25):"""将文件按指定大小(GB)分组"""max_size_bytes = max_size_gb * 1024 * 1024 * 1024 # GB转换为字节groups = []current_group = []current_size = 0for file in file_list:file_size = os.path.getsize(file)# 如果当前组加上新文件超出限制,且当前组不为空,则新建一组if current_size + file_size > max_size_bytes and current_group:groups.append(current_group)current_group = []current_size = 0current_group.append(file)current_size += file_size# 添加最后一组if current_group:groups.append(current_group)return groups# 使用7-Zip压缩一组文件
def compress_files(group, output_file, seven_zip_path, password=None):"""调用7-Zip压缩一组文件,可选设置密码"""# 检查7-Zip是否可用if not os.path.exists(seven_zip_path):print("错误:请检查7-Zip安装路径是否正确!")return# 构建7-Zip命令command = [seven_zip_path,"a", # 添加到压缩包"-t7z", # 使用7z格式output_file, # 输出文件名]if password: # 如果设置了密码command.extend(["-p{}".format(password), "-mhe=on"]) # 添加密码并加密文件名command.extend(group) # 添加文件列表# 执行压缩try:result = subprocess.run(command, capture_output=True, text=True)if result.returncode == 0:print(f"压缩成功:{output_file}")else:print(f"压缩失败:{result.stderr}")except Exception as e:print(f"发生错误:{str(e)}")# 主函数
def main():# 配置参数seven_zip_path = r"D:\Program Files\7-Zip\7z.exe" # 7-Zip安装路径,可根据需要修改folder_path = r"D:\MyFiles" # 要压缩的文件夹路径output_dir = r"D:\CompressedFiles" # 压缩包保存目录max_size_gb = 25 # 每组最大大小(GB)password = "mysecret123" # 压缩密码(可选,留空则无密码)# 创建输出目录(如果不存在)if not os.path.exists(output_dir):os.makedirs(output_dir)# 获取文件列表files = get_all_files(folder_path)if not files:print("错误:文件夹中没有文件!")return# 分组文件file_groups = group_files_by_size(files, max_size_gb)# 压缩每组文件for i, group in enumerate(file_groups, start=1):output_file = os.path.join(output_dir, f"Part_{i}.7z")print(f"正在压缩第 {i} 组文件...")compress_files(group, output_file, seven_zip_path, password)if __name__ == "__main__":main()
代码如何工作?
-
get_all_files
- 使用
os.walk
遍历文件夹,收集所有文件的完整路径。 - 适用于任何文件类型,不局限于视频。
- 使用
-
group_files_by_size
- 根据文件大小(字节)将文件分组。
- 每组大小不超过
max_size_gb
,通过累加文件大小判断是否需要新建一组。
-
compress_files
- 使用
subprocess.run
调用7-Zip,执行压缩命令。 - 支持可选密码保护,加密文件名(
-mhe=on
)。
- 使用
-
main
- 设置输入文件夹、输出目录、分组大小和密码。
- 按顺序处理每组文件,生成独立的压缩包。