如何用Python脚本加密大体积文件?解决MemoryError问题
解决大文件加密时的MemoryError问题
原脚本处理小体积、少量文件时能正常完成加密,但处理大体积或大量文件时,执行contents = thefile.read()会抛出MemoryError——原因是一次性将整个文件内容加载到内存,当文件体积超过可用内存上限时就会触发该错误。
解决方案:分块读取加密
通过分块读取文件内容,每次只处理一小部分数据,避免占用过多内存。修改后的脚本如下:
import os from cryptography.fernet import Fernet your_files = [] # 遍历目标目录收集文件 for root, dirs, files in os.walk("E:/test4"): for file in files: print(f"文件名: {file}") # 跳过指定文件和Python脚本 if file == "log" or file.endswith(".py"): continue full_file_path = os.path.join(root, file) your_files.append(full_file_path) print(f"完整路径: {full_file_path}") print(f"待处理文件列表: {your_files}") # 生成并保存密钥 key = Fernet.generate_key() with open("thekey.key", "wb") as thekey: thekey.write(key) fernet = Fernet(key) file_exts = [".log", ".chm"] # 分块大小设置为64KB,可根据内存情况调整 CHUNK_SIZE = 64 * 1024 for file in your_files: # 简化文件后缀判断 if any(file.endswith(ext) for ext in file_exts): # 临时文件存储加密后的内容,避免覆盖原文件过程中出错 temp_file = f"{file}.tmp" try: with open(file, "rb") as infile, open(temp_file, "wb") as outfile: while True: chunk = infile.read(CHUNK_SIZE) if not chunk: break # 分块加密并写入临时文件 encrypted_chunk = fernet.encrypt(chunk) outfile.write(encrypted_chunk) # 替换原文件 os.replace(temp_file, file) print(f"已加密文件: {file}") except Exception as e: print(f"加密文件 {file} 失败: {str(e)}") # 清理临时文件 if os.path.exists(temp_file): os.remove(temp_file) print("所有目标文件已完成加密")
关键改进点:
- 分块读取:使用固定大小的分块(64KB)循环读取文件,每次只将一小部分数据加载到内存。
- 临时文件处理:先将加密内容写入临时文件,确认加密完成后再替换原文件,避免原文件因加密失败损坏。
- 简化后缀判断:用
any()替代嵌套循环,代码更简洁高效。 - 预初始化Fernet实例:避免在循环中重复创建Fernet对象,提升性能。
内容的提问来源于stack exchange,提问作者Jokey
相关产品推荐
相关产品推荐

