在Python中加密压缩文件可以通过多种方式实现,以下是几种常见的方法:
方法一:使用7-Zip命令行工具
1. 安装7-Zip程序。
2. 使用Python的`subprocess`模块调用7-Zip命令行工具进行加密压缩。
示例代码如下:
import osimport subprocessdef my7zip(zDir, zPass, zipFileName):appPath = r"C:\Program Files\7-Zip"zApp = "7z.exe"zAction = "a"zAnswer = "-y"command = f'"{appPath}\{zApp}" {zAction} "{zipFileName}" -p{zPass} "{zDir}"'subprocess.run(command, shell=True, check=True)zDir = [r"E:\tmp\我的文件夹", r"E:\tmp\我的文件.docx"]zPass = "-pailx10"zipFileName = "加密文件和文件夹_{}.zip".format(time.time())my7zip(zDir, zPass, zipFileName)
方法二:使用`minizip`和`zlib`
1. 下载`minizip`和`zlibwapi.dll`。
2. 使用Python的`os.system`或`subprocess`模块调用`minizip`进行加密压缩。
示例代码如下:
import osdef createEncryptedFile(password, zipfile_path, source_path):cmd = f'"{minizip_path}" -o -1 -p {password} "{zipfile_path}" "{source_path}"'os.system(cmd)minizip_path = "your_path_to_minizip" 替换为minizip.exe的实际路径createEncryptedFile("mypassword", "encrypted.zip", "source_folder")

方法三:使用WinRAR命令行工具
1. 安装WinRAR程序。
2. 使用Python的`subprocess`模块调用WinRAR命令行工具进行加密压缩。
示例代码如下:
import osimport subprocessdef createWinRAREncryptedFile(password, output_path, source_path):rarPath = "C:\\Program Files\\WinRAR\\WinRAR.exe" WinRAR的安装路径command = f'"{rarPath}" a -p{password} "{output_path}" "{source_path}"'subprocess.run(command, shell=True, check=True)output_path = "encrypted.rar"source_path = "source_folder"createWinRAREncryptedFile("mypassword", output_path, source_path)
方法四:使用Python的`zipfile`模块
1. 使用Python的`zipfile`模块进行加密压缩。
示例代码如下:
import zipfiledef createZipFileWithPassword(filename, password):with zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED) as zf:zf.setpassword(password.encode())zf.write('file_to_compress.txt')filename = "encrypted.zip"password = "mypassword"createZipFileWithPassword(filename, password)
以上方法均可实现文件的加密压缩,选择适合自己需求的方法即可。需要注意的是,对于大型文件或文件夹,可能需要考虑执行时间和系统资源消耗
