# Uncompress archive, check contents, add missing files, recompress archive

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

with tarfile.open(outfeil, 'a') as tar:
for ntLI in ntlist:

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.')

• Not making these procedures into functions makes it difficult to reuse your code. – Aaron Hall Jan 30 '16 at 17:10
• I have rolled back the last edit. Please see What to do when someone answers. – Peilonrayz Jan 30 '16 at 20:37

### Remove unecessary code

myDirList is assigned but never used, delete it:

myDirList = os.chdir('/home/pi/python/chap9OrganizingFiles/shutildir/')


You do not need to build a list as:

for dirList in os.listdir(os.getcwd()):
myFL.append(dirList)
for listItem in myFL:


You can iterate over os.listdir(os.getcwd()) directly:

for listItem in os.listdir(os.getcwd()):

• I'll do that, thanks for pointing that out. Appreciated. – user95110 Jan 30 '16 at 19:57
• @Dimurof82 I suggest waiting some days before accepting, a better answer may come along. – Caridorc Jan 31 '16 at 14:44
• Thanks, ill see what comes along. If nothing better, its yours. – user95110 Jan 31 '16 at 14:45