如何在python中使用shutil.make_存档压缩文件?
我想使用如何在python中使用shutil.make_存档压缩文件?,python,compression,Python,Compression,我想使用shutil.make_archive命令压缩一个文本文件。我正在使用以下命令: shutil.make_archive('gzipped'+fname, 'gztar', os.path.join(os.getcwd(), fname)) OSError: [Errno 20] Not a directory: '/home/user/file.txt' 我尝试了几种变体,但它一直试图压缩整个文件夹。如何正确地做 试试这个并检查一下 将文件复制到一个目录 光盘目录 shutil.m
shutil.make_archive
命令压缩一个文本文件。我正在使用以下命令:
shutil.make_archive('gzipped'+fname, 'gztar', os.path.join(os.getcwd(), fname))
OSError: [Errno 20] Not a directory: '/home/user/file.txt'
我尝试了几种变体,但它一直试图压缩整个文件夹。如何正确地做 试试这个并检查一下
将文件复制到一个目录
光盘目录
shutil.make_archive('gzipped', 'gztar', os.getcwd())
shutil
无法从一个文件创建存档。您可以改用tarfile
:
tar = tarfile.open(fname + ".tar.gz", 'w:qz')
os.chdir('/home/user')
tar.add("file.txt")
tar.close()
或
其实可以做一个文件存档!只需将目标目录的路径传递为root\u dir
,目标文件名传递为base\u dir
试试这个:
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
如果您不介意执行文件复制操作:
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)
@CommonSense给出了一个很好的答案,但是文件总是在其父目录中压缩创建的。如果需要创建没有额外目录的zipfile,只需直接使用
zipfile
模块即可
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))
将file.txt复制到一个目录,并尝试在该目录上调用该文件。什么目录?file.txt在
/home/user
中,该文件的最低版本是什么?在Python2.7.6中,提供一个文件名作为base_dir会导致一个空的zip文件
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))