How do I compress a folder with the Python GZip module?

£可爱£侵袭症+ 提交于 2019-12-07 02:06:02

问题


I'm creating Python software that compresses files/folders... How would I create a section of the code that asks for the user input of the folder location and then compresses it. I currently have the code for a single file but not a folder full of files. Please explain in detail how to do this.


回答1:


The code to compress a folder in to tar file is:

import tarfile

tar = tarfile.open("TarName.tar.gz", "w:gz")
tar.add("folder/location", arcname="TarName")
tar.close()

It works for me. Hope that works for you too.




回答2:


GZip doesn't do compression of folders/directories, only single files. Use the zipfile module instead.




回答3:


I don't do UI, so you're on your own for getting the folder name from the user. Here's one way to make a gz-compressed tarfile. It does not recurse over subfolders, you'll need something like os.walk() for that.

# assume the path to the folder to compress is in 'folder_path'

import tarfile
import os

with tarfile.open( folder_path + ".tgz", "w:gz" ) as tar:
    for name in os.listdir( folder_path ):
        tar.add(name)



回答4:


As larsmans says, gzip compression is not used for directories, only single files. The usual way of doing things with linux is to put the directory in a tarball first and then compress it.



来源:https://stackoverflow.com/questions/3874837/how-do-i-compress-a-folder-with-the-python-gzip-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!