tastyminerals
tastyminerals

Reputation: 6538

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

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?

Upvotes: 15

Views: 26339

Answers (6)

Ferris
Ferris

Reputation: 101

Archiving a directory to another destination was a pickle for me but shutil.make_archive not zipping to correct destination helped a lot.

from shutil import make_archive
make_archive(
    base_name=path_to_directory_to_archive},
    format="gztar",
    root_dir=destination_path,
    base_dir=destination_path)

Upvotes: 0

user2682863
user2682863

Reputation: 3217

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

Upvotes: 1

CommonSense
CommonSense

Reputation: 4482

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

Upvotes: 26

Oliver Zendel
Oliver Zendel

Reputation: 2901

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)

Upvotes: 0

Kirikami
Kirikami

Reputation: 331

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

Upvotes: 5

Ajay
Ajay

Reputation: 5347

Try this and Check shutil

copy your file to a directory.

cd directory

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

Upvotes: 4

Related Questions