天天看點

tarfile子產品可以方操作tar歸檔檔案

# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#Python自帶的tarfile子產品可以友善讀取tar歸檔檔案
#http://www.open-open.com/lib/view/open1398334415312.html


#歸檔檔案定義:
#歸檔檔案是一個檔案和目錄的集合,而這個集合被存儲在一個檔案中,歸檔檔案沒有經過壓縮,其所使用的磁盤空間是其中所有檔案和目錄的總和。


#歸檔檔案用途:常用于文檔的備份。



import tarfile,os
 
#建立壓縮包名
tar = tarfile.open("tarTest.tar.gz","w:gz")
#建立壓縮包
#)os.walk:
#可以得到一個三元tupple(dirpath, dirnames, filenames),
#其中第一個為起始路徑,第二個為起始路徑下的檔案夾,第三個是起始路徑下的檔案
for root,dir,files in os.walk(r"D:Python"):
    for file in files:
        fullpath = os.path.join(root,file)
        tar.add(fullpath)
tar.close()



#進行讀取操作并解壓tar.gz檔案
f=tarfile.open("tarTest.tar.gz","r:gz")
names=f.getnames()#傳回所有的檔案名字
for name in names:
    f.extract(name,path=r'C:1')#path表示解壓檔案到什麼路徑中
f.close()