Search code examples
pythonzip7ziprar

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


How can I convert a .7z file to a .rar or a .zip file using Python?


Solution

  • You can do this in two steps. First, uncompress the .7z file and then compress the content to zip file.

    Uncompress .7z file

    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')
    

    Reference: https://github.com/harvimt/pylib7zip

    Compress to zip file

    #!/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()