[Tutor] tarfile library question
alexkleider
alexkleider at protonmail.com
Wed Dec 9 21:30:25 EST 2020
I have written the following code as an archiving utility to serve my needs:
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:
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!")
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?
2. why are <res> and <destination_directory> not considered equal?
Thanks in advance for any light that can be shed.
Cheers,
Alex Kleider
More information about the Tutor
mailing list