[Tutor] tarfile library question
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Dec 10 05:10:23 EST 2020
On 10/12/2020 02:30, alexkleider via Tutor wrote:
> I have written the following code as an archiving utility to serve my needs:
You've lost the formatting so its difficult to tell where your with and
for blocks end. ie how much is inside each block...
>
> import os
> import shutil
> import tarfile
>
> def archive(destination_directory, source, targz_base_name):
> """
> Create a <targz_base_name>.tar.gz archive and
> file it in the <destination_directory>.
> The archive is to contain all files &/or directories
> listed in <source> (a list.)
> Fails if a directory <targz_base_name> already exists.
> A directory of this name is created as a temporary place to
> gather what is to be archived.
> """
> os.mkdir(targz_base_name)
> for folder in list_of_targets:
Where does list_of_targets come from?
> shutil.copytree(folder,
> os.path.join(targz_base_name, folder),
> )
> tar_file = "{}.tar.gz".format(targz_base_name)
> with tarfile.open(tar_file, "w:gz") as tar:
> tar.add(targz_base_name)
>
> shutil.rmtree(targz_base_name)
>
> res = shutil.move(tar_file, destination_directory)
> if not (res == destination_directory):
> print("The following two strings:")
> print("\t'{}'".format(res))
> print("\t'{}'".format(os.path.join(destination_directory,
> tar_file)))
> print("look the same to me but not to Python!! Beats me why!")
So what output do you get?
>
> I have two questions.
>
> 1. is there a way of writing the code so as to eliminate the need to
> create and populate a temporary directory and instead create the parent
> directory and then populate it all within the "with...as tar" clause?
Probably. You need a loop over the target folders somewhere
inside the open and you need to append to the tar file
not write to it.
> 2. why are <res> and <destination_directory> not considered equal?
Don't know, show us some sample output.
Also, try printing the repr() of the names as well as the str() versions.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list