1. 程式人生 > >使用Python解壓縮tar文件的方法

使用Python解壓縮tar文件的方法

1、 tarfile包中的.open(name, mode)方法可以以mode指定的方式開啟name壓縮檔案,並返回一個TarFile類物件。呼叫TarFile物件的extractall(path)方法可以將tar文件解壓到path指定的位置。

import tarfile
tar = tarfile.open( '*.tar.gz', mode = "r:gz") #"r:gz"表示 open for reading with gzip compression
tar.extractall(path='temp')  ### 將tar.gz檔案解壓到temp資料夾下
tar.close()

open返回的物件不但可以用來讀文件資料('r': reading),還可以寫('w': writing),附加('a': appending)。

如下是mode取值所對應的含義:

'r' or 'r:*' open for reading with transparent compression
'r:'         open for reading exclusively uncompressed
'r:gz'       open for reading with gzip compression
'r:bz2'      open for reading with bzip2 compression
'r:xz'       open for reading with lzma compression
'a' or 'a:'  open for appending, creating the file if necessary
'w' or 'w:'  open for writing without compression
'w:gz'       open for writing with gzip compression
'w:bz2'      open for writing with bzip2 compression
'w:xz'       open for writing with lzma compression

'x' or 'x:'  create a tarfile exclusively without compression, raise
             an exception if the file is already created
'x:gz'       create a gzip compressed tarfile, raise an exception
             if the file is already created
'x:bz2'      create a bzip2 compressed tarfile, raise an exception
             if the file is already created
'x:xz'       create an lzma compressed tarfile, raise an exception
             if the file is already created

'r|*'        open a stream of tar blocks with transparent compression
'r|'         open an uncompressed stream of tar blocks for reading
'r|gz'       open a gzip compressed stream of tar blocks
'r|bz2'      open a bzip2 compressed stream of tar blocks
'r|xz'       open an lzma compressed stream of tar blocks
'w|'         open an uncompressed stream for writing
'w|gz'       open a gzip compressed stream for writing
'w|bz2'      open a bzip2 compressed stream for writing
'w|xz'       open an lzma compressed stream for writing