Search code examples
python-2.7tarfile

Reading .tar.Z file without decompressing in Python 2.7


I am new to Python and trying to read .tar.Z file name and trying to list the file names compressed inside it. I just need to know the file name and size. I am using Python 2.7. I am able to do it with .tar file. Can somebody explain that with an example?

Thanks


Solution

  • The compress command and its .Z files is so antiquated that Python doesn't support it directly (and likely never did).

    I suggest

    #!/bin/sh
    for i in *.tar.Z; do
        tarname=`basename "$i" .Z`
        uncompress "$i"
        gzip "$tarname"
    done
    

    Then you can just open the tarfiles as shown in the documentation with the 'r:gz' mode.

    If you don't want to migrate away from 1980s compress technology, then you should probably look into

    zcat tarfile.tar.Z | tar tf -
    

    using the subprocess module.

    (For those who are tempted to say "but bzip2 is better" or "but xz is supported in Python 3", yeah, I agree, but gzip is simply more standard).