How do I extract a tar file using python 2.4?

后端 未结 2 1454
陌清茗
陌清茗 2021-01-08 00:42

I\'m trying to extract a .tar file completely using python 2.4.2 and because of this not all of the aspects of the tarfile module are usable. I\'ve looked through the python

2条回答
  •  长情又很酷
    2021-01-08 01:31

    This example is from the tarfile docs.

    import tarfile
    tar = tarfile.open("sample.tar.gz")
    tar.extractall()
    tar.close()
    

    First, a TarFile object is created using tarfile.open(), then all files are extracted using extractall() and finally the object is closed.

    If you want to extract to a different directory, use extractall's path parameter:

    tar.extractall(path='/home/connor/')
    

    Edit: I see now that you are using an old Python version which doesn't have the TarFile.extractall() method. The documentation for older versions of tarfile confirms this. You can instead do something like this:

    for member in tar.getmembers():
        print "Extracting %s" % member.name
        tar.extract(member, path='/home/connor/')
    

    If your tar file has directories in it, this probably fails (I haven't tested it). For a more complete solution, see the Python 2.7 implementation of extractall

    Edit 2: For a simple solution using your old Python version, call the tar command using subprocess.call

    import subprocess
    tarfile = '/path/to/myfile.tar'
    path = '/home/connor'
    retcode = subprocess.call(['tar', '-xvf', tarfile, '-C', path])
    if retcode == 0:
        print "Extracted successfully"
    else:
        raise IOError('tar exited with code %d' % retcode)
    

提交回复
热议问题