The code looks for the specified .tgz file, if it's not present, it creates it. It looks for files ending in .txt in the cwd and adds them to a list. It decompresses the gzip, checks for the .txt files in the tar, adds the missing files to the tar and then recreates the compressed gzip with the new files in it. It then deletes the temporarily created tar file.
This is a self assigned script to learn the basics of working with compressed tarballs.
Please take a look and let me know if there are problems that can be accounted for or improvements that can be made. I'm only a few weeks into python, there is still a lot that I don't know.
#!usr/bin/python3 import os, gzip import tarfile import sys import shutil import send2trash myFL =  notThere =  feil = '/home/pi/python/chap9OrganizingFiles/shutildir/comp.tgz' outfeil = '/home/pi/python/chap9OrganizingFiles/shutildir/comp.tar' if os.path.isfile(feil): print('File found, opening ' + os.path.relpath(feil)) else: print('File does NOT exist, creating ' + os.path.relpath(feil)) with tarfile.open(feil, 'w:gz'): print('File Created') with tarfile.open(feil, 'r:gz') as tar: myDirList = os.chdir('/home/pi/python/chap9OrganizingFiles/shutildir/') print('Current directory is: ' + os.getcwd() + '\n\n') for dirList in os.listdir(os.getcwd()): myFL.append(dirList) for listItem in myFL: if listItem in tar.getnames(): print("There: " + listItem) else: if listItem.endswith('.txt'): notThere.append(listItem) print('\n\n') for li in notThere: print('Text file not in tarball: ' + li) with gzip.open(feil, 'rb') as unzip, open(outfeil, 'wb') as out:# open the gzip file out.write(unzip.read()) # read the gzip file into the output file def addToTar(ntlist): with tarfile.open(outfeil, 'a') as tar: for ntLI in ntlist: tar.add(ntLI) print('Item added: ' + ntLI) addToTar(notThere) with open(outfeil, 'rb') as uf, gzip.open('/home/pi/python/chap9OrganizingFiles/shutildir/comp.tgz', 'wb') as of: shutil.copyfileobj(uf, of) send2trash.send2trash(outfeil) print('\nAll done and cleaned up.')