I'm trying to tar all the subdirectories in a directory as separate files and use the subdir name as the file name but I can't get it work.
import os
import tarfile
mypath = "/home/somedir"
def tardir(path):
for d in os.listdir(path):
tar_name = d + ".tar.gz"
print (tar_name)
for root, dirs, files in os.walk(path):
for file in files:
print (file)
with tarfile.open(tar_name, "w") as tar_handle:
tar_handle.add(file)
tardir(mypath)
Here is my final code.
path = "/home/dir/files/test/"
for base, dirs, _ in os.walk(path):
for d in dirs:
with tarfile.open(path + d + '.tar.gz', 'w:gz') as tar:
for _, _, files in os.walk(path + d):
for f in files:
tar.add(os.path.join(path, d, f), arcname= f)