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?
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With