How to compress a file with shutil.make_archive in python?

微笑、不失礼 提交于 2021-01-27 07:32:44

问题


I want to compress one text file using shutil.make_archive command. I am using the following command:

shutil.make_archive('gzipped'+fname, 'gztar', os.path.join(os.getcwd(), fname))

OSError: [Errno 20] Not a directory: '/home/user/file.txt'

I tried several variants but it keeps trying to compress the whole folders. How to do it correctly?


回答1:


shutil can't create an archive from one file. You can use tarfile, instead:

tar = tarfile.open(fname + ".tar.gz", 'w:qz')
os.chdir('/home/user')
tar.add("file.txt")
tar.close()

or

tar = tarfile.open(fname + ".tar.gz", 'w:qz')
tar.addfile(tarfile.TarInfo("/home/user/file.txt"), "/home/user/file.txt")
tar.close()



回答2:


Actually shutil.make_archive can make one-file archive! Just pass path to target directory as root_dir and target filename as base_dir.

Try this:

import shutil

file_to_zip = 'test.txt'            # file to zip
target_path = 'C:\\test_yard\\'     # dir, where file is

try:
    shutil.make_archive(target_path + 'archive', 'zip', target_path, file_to_zip)
except OSError:
    pass



回答3:


Try this and Check shutil

copy your file to a directory.

cd directory

shutil.make_archive('gzipped', 'gztar', os.getcwd())



回答4:


If you don't mind doing a file copy op:

def single_file_to_archive(full_path, archive_name_no_ext):
    tmp_dir = tempfile.mkdtemp()
    shutil.copy2(full_path, tmp_dir)
    shutil.make_archive(archive_name_no_ext, "zip", tmp_dir, '.')
    shutil.rmtree(tmp_dir)



回答5:


@CommonSense had a good answer, but the file will always be created zipped inside its parent directories. If you need to create a zipfile without the extra directories, just use the zipfile module directly

import os, zipfile
inpath  = "test.txt"
outpath = "test.zip"
with zipfile.ZipFile(outpath, "w", compression=zipfile.ZIP_DEFLATED) as zf:
    zf.write(inpath, os.path.basename(inpath))


来源:https://stackoverflow.com/questions/30049201/how-to-compress-a-file-with-shutil-make-archive-in-python

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