2015-07-01 33 views
3

我試圖提取一個.tar文件完全使用python 2.4.2,因爲這不是tarfile模塊的所有方面都可用。我已經瀏覽了python紀錄片,並且我還沒有發現它會對我有用,因爲我會繼續犯下語法錯誤。以下是我試過的命令(不成功):如何使用python 2.4提取tar文件?

tarfile.Tarfile.getnames(tarfile.tar) 
tarfile.Tarfile.extract(tarfile.tar) 

是否有一種簡單的方法可以完全提取我的焦油?如果是這樣的格式是什麼?另外,我想指出tarfile.TarFile.extractall()在我的Python版本中不可用。

回答

9

本示例來自tarfile文檔。

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

首先,使用tarfile.open()創建tar文件對象,那麼所有文件都使用extractall()提取和最後的對象被關閉。

如果要提取到不同的目錄,使用extractall's path parameter

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

編輯:(?< 2.5你能更具體)我,現在你使用的是舊版本的Python見它沒有TarFile.extractall()方法。 documentation for older versions of tarfile證實了這一點。你可以代替做這樣的事情:

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

如果你的tar文件中有目錄,這可能失敗(我沒有測試過)。爲了更完整的解決方案,請參閱Python 2.7 implementation of extractall

編輯2:對於使用舊版本的Python一個簡單的解決方案,使用調用tar commandsubprocess.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)