Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 224
minerals Avatar asked May 05 '15 09:05

minerals


People also ask

How do I compress a file in Python?

To create your own compressed ZIP files, you must open the ZipFile object in write mode by passing 'w' as the second argument. When you pass a path to the write() method of a ZipFile object, Python will compress the file at that path and add it into the ZIP file.

How do I zip a file in ZipFile Python?

To compress individual files into a ZIP file, create a new ZipFile object and add the files you want to compress with the write() method. With zipfile. ZipFile() , specify the path of a newly created ZIP file as the first parameter file , and set the second parameter mode to 'w' (write).

What is the use of Rmtree ()?

rmtree() is used to delete an entire directory tree, path must point to a directory (but not a symbolic link to a directory). Parameters: path: A path-like object representing a file path.


1 Answers

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
like image 163
CommonSense Avatar answered Sep 22 '22 07:09

CommonSense