Python: 如何将 .7z 转换为 .rar 或 .zip?

Python: How to convert .7z to .rar or .zip?

如何使用 Python 将 .7z 文件转换为 .rar 或 .zip 文件?

您可以分两步完成此操作。首先,解压缩.7z 文件,然后将内容压缩为 zip 文件。

解压缩 .7z 文件

from lib7zip import Archive, formats

with Archive('filename.7z') as archive:
    # extract all items to the directory
    # directory will be created if it doesn't exist
    archive.extract('directory')

参考:https://github.com/harvimt/pylib7zip

压缩为 zip 文件

#!/usr/bin/env python
import os
import zipfile

def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))

if __name__ == '__main__':
    zipf = zipfile.ZipFile('file.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('tmp/', zipf)
    zipf.close()