minerals minerals - 1 year ago 228
Python Question

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?

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download