[Tutor] .tar.gz in Py (was: do pythons like coffee?)

Nick Lunt nick at javacat.f2s.com
Sat Jan 31 17:21:26 EST 2004

Hi Andrei,

I asked a tar question myself yesterday and included my problematic program. Here it is -


        tar.py filetocreate.tar list_of_files_to_tar

        tarfile -        to do the tarring
        sys -            to manipulate command line args        

# Fails in the if block on os.access when dirs are submitted as args.
# ie the dir submitted is readable but some files below it may not be,
# which the if os.access() does not pick up.
# So create a new function to walk the dir and only return the files it can
# backup successfully, but print a list of the ones it cant.

import tarfile, sys, os

if len(sys.argv) <= 2:
        print 'Error:', sys.argv[0], ' <tarfile.tar> <list of files to tar>'

tfile = sys.argv[1]

totar = []
for f in sys.argv[2:]:
        if os.access(f, os.R_OK):
                print 'Could not access', f, 'to tar'

tf = tarfile.TarFile(tfile, 'w')
for f in totar:



As you can see from the comments in my code it is not perfect yet, but it will hopefully show you how to use the tar module, and it will create a tar file for you.

There is also a gzip module you can import to gzip the tar file, but I've not got my head round that yet as the tar part is not 100%, but that is my plans for it. Then it's going to write it to CD. Then I'd like to make a GUI for it, just to learn how to ;) Oh yeah, the final version is also gonna be OOP.

Hope that helps a bit,

On Sat, 31 Jan 2004 22:29:18 +0100
Andrei <project5 at redrival.net> wrote:

> Hi,
> I have a batch file in which I create a tar.gz file of a directory
> containing nested subdirectories (and files) using the 7-zip command line,
> like this:
> 7z.exe a -ttar ..\myfile.tar * -r
> cd..
> 7z.exe a -tgzip myfile.tar.gz myfile.tar -r
> The result then looks somewhat like this:
>   - myfile.tar.gz
>        |
>        |- myfile.tar
>              |
>              |- file1.ext
>              |- dir1
>                    |
>                    |-file2.ext
> Python has a tarfile module so I was thinking I'd like to migrate that to
> Python (not just by running os.system()) because I use it in building a
> distro for a program. The problem is that the docs for the tarfile module
> don't seem to fit my brain and I also can't find any decent sample code. 
> Does anyone know any examples for using the tarfile module?
> -- 
> Yours,
> Andrei
> =====
> Mail address in header catches spam. Real contact info (decode with rot13):
> cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
> gur yvfg, fb gurer'f ab arrq gb PP.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list