如何在python中使用shutil.make_archive压缩文件? [英] How to compress a file with shutil.make_archive in python?

查看:46
本文介绍了如何在python中使用shutil.make_archive压缩文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 shutil.make_archive 命令压缩一个文本文件.我正在使用以下命令:

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?

推荐答案

shutil 无法从一个文件创建存档.您可以使用 tarfile ,代替:

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

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

这篇关于如何在python中使用shutil.make_archive压缩文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆