Python的压缩文件处理 zipfile tarfile
本文從以下兩個方面, 闡述Python的壓縮文件處理方式:
一.?zipfile
二.?tarfile
?
一.?zipfile
雖然叫zipfile,但是除了zip之外,rar,war,jar這些壓縮(或者打包)文件格式也都可以處理。
zipfile模塊常用的一些操作和方法:
is_zipfile(filename) 測試filename的文件,看它是否是個有效的zipfile
ZipFile(filename[,mode[,compression[,allowZip64]]]) 構造zipfile文件對象。mode可選r,w,a代表不同的打開文件的方式。compression指出這個zipfile用什么壓縮方法,默認是ZIP_STORED,另一種選擇是ZIP_DEFLATED。allowZip64是個bool型變量,當設置為True的時候就是說可以用來創建大小大于2G的zip文件,默認值是True
ZipInfo 包含一個zip文件中的子文件的信息,字段包括filename(包括相對zip包的路徑),date_time(一個時間元組,該子文件最后修改時間),compress_type(該子文件的壓縮格式)等等。
?
對于ZipFile實例z,有以下方法:
z.close() 關閉文件
z.extract(name[,path[,pwd]]) 從zip中提取一個文件,將它放到指定的path下,pwd是密碼,用于被加密的zip文件
z.extractall(path[,pwd]) 將所有文件按照namelist中顯示得那樣的目錄結構從當前zip中提取出來并放到path下。//這兩個extract的path若不存在都會自動創建出來的,且這個path必須是個目錄,解壓時一定是把一個文件,包含其相對zip包路徑的所有目錄一起解壓出來??傊悬c坑,自己測試一下就知道了
z.namelist() 返回一個列表,內容是zip文件中所有子文件的path(相對于zip文件包而言的)。相當于是一個保存了zip內部目錄結構的列表
z.infolist() 返回一個列表,內容是每個zip文件中子文件的ZipInfo對象,這個對象有上文中提到的那些字段
z.printdir() 將zip文件的目錄結構打印到stdout上,包括每個文件的path,修改時間和大小
z.open(name[,mode[,pwd]]) 獲取一個子文件的文件對象,可以將其用來read,readline,write等等操作
z.setpassword(psw) 可以為zip文件設置默認密碼
z.testzip() 讀取zip中的所有文件,驗證他們的CRC校驗和。返回第一個損壞文件的名稱,如果所有文件都是完整的就返回None
z.write(filename[,arcname[,compression_type]]) 將zip外的文件filename寫入到名為arcname的子文件中(當然arcname也是帶有相對zip包的路徑的),compression_type指定了壓縮格式,也是ZIP_STORED或ZIP_DEFLATED。z的打開方式一定要是w或者a才能順利寫入文件。
?
貼上兩個已經寫好的常用的解壓縮和壓縮函數:
壓縮一個目錄:
def zip_dir(dirname,zipfilename):filelist = []if os.path.isfile(dirname):filelist.append(dirname)else :for root, dirs, files in os.walk(dirname):for dir in dirs:filelist.append(os.path.join(root,dir))for name in files:filelist.append(os.path.join(root, name))zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)for tar in filelist:arcname = tar[len(dirname):]#print arcnamezf.write(tar,arcname)zf.close()?
解壓縮一個文件:(轉自http://blog.csdn.net/linda1000/article/details/10432133)
def unzip_dir(zipfilename, unzipdirname): fullzipfilename = os.path.abspath(zipfilename) fullunzipdirname = os.path.abspath(unzipdirname) print "Start to unzip file %s to folder %s ..." % (zipfilename, unzipdirname) #Check input ... if not os.path.exists(fullzipfilename): print "Dir/File %s is not exist, Press any key to quit..." % fullzipfilename inputStr = raw_input() return if not os.path.exists(fullunzipdirname): os.mkdir(fullunzipdirname) else: if os.path.isfile(fullunzipdirname): print "File %s is exist, are you sure to delet it first ? [Y/N]" % fullunzipdirname while 1: inputStr = raw_input() if inputStr == "N" or inputStr == "n": return else: if inputStr == "Y" or inputStr == "y": os.remove(fullunzipdirname) print "Continue to unzip files ..." break #Start extract files ... srcZip = zipfile.ZipFile(fullzipfilename, "r") for eachfile in srcZip.namelist():if eachfile.endswith('/'):# is a directoryprint 'Unzip directory %s ...' % eachfilenameos.makedirs(os.path.normpath(os.path.join(fullunzipdirname, eachfile)))continue print "Unzip file %s ..." % eachfile eachfilename = os.path.normpath(os.path.join(fullunzipdirname, eachfile)) eachdirname = os.path.dirname(eachfilename) if not os.path.exists(eachdirname): os.makedirs(eachdirname) fd=open(eachfilename, "wb") fd.write(srcZip.read(eachfile)) fd.close() srcZip.close() print "Unzip file succeed!"?
二.?tarfile
linux上常用的tar文件不被zipfile支持,應該要用tarfile模塊來處理tar文件,無論tar文件是否被壓縮還是僅僅被打包,都可以讀取和寫入tar文件。和zipfile模塊類似的。
? ? ? ?Tarfile有以下一些方法和類:
is_tarfile(filename) 檢查是否是個有效的tar文件
open([name[,mode]]) 和zipfile的ZipFile有所不同的是,這里的open除了指出打開文件的方式以外還指出了文件的壓縮方式。通過filemode[:compression]的方式可以指出很多種文件模式:
'r' 讀打開,如果文件是壓縮得會被透明(???)地解壓縮。這是默認打開方式
'r:' 讀打開,不壓縮文件
'r:gz' 讀打開,使用gzip壓縮文件
'r:bz2' 讀打開,使用bzip2壓縮文件
'a','a:' 追加打開,不壓縮文件 //注意,a模式下不能加壓縮格式的。如果想要給壓縮包添加什么東西的話最好另尋他路
'w','w:' 寫打開,不壓縮文件
'w:gz' 寫打開,使用gzip壓縮文件
'w:bz2' 寫打開只用bzip2壓縮文件
TarInfo類對象 和ZipInfo類似的,一個子文件的TarInfo對象存儲了這個子文件的一些信息。
? ? ? ?TarInfo對象有一些方法和屬性:
it.gid/gname 獲取這個子文件的組ID和組名稱
it.uid/uname 獲取這個子文件的用戶id和用戶名稱
ti.isdir() 判斷這個子文件是否是個目錄
ti.isfile() 判斷是否是個普通文件
ti.name 文件名
ti.mode 權限
ti.size 大小
ti.mtime 最后修改時間
?
由open返回的一個tarfile實例t有以下方法:
t.add(name[,arcname,[recursive]]) 將tar包外的文件或目錄name添加到tar包內的arcname,當name是個目錄時可把recursive設置為True來遞歸地加入tar包
t.close()
t.errorlevel 可以設置提取tar包中文件時如何確定處理錯誤,當這一屬性為0時,錯誤將被忽略,為1時錯誤將導致IOError和OSError,如果設置為2非致命性錯誤將會導致TarError
t.extract(member[,path]) 從tar包中提取一個子文件,保存到指定目錄下
t.extractfile(member) 從tar包中提取一個子文件,但返回的是個類文件對象,可以通過read,write等方法來操作文件的內容
t.getnames() 類似于zipfile中的namelist()
t.ignore_zeros 若這一個屬性被設置為True的話,讀取tar包時會跳過空塊,如果這已設置為False則空塊表示tar包的結束。這個屬性的設置有利于讀取損壞的tar包
t.list() 類似于zipfile的printdir(),但是其列出的信息更加詳細,如果不要這么詳細的信息,可以加上參數False
t.getmemebers() 返回一個列表,內容是所有文件的TarInfo對象
?
參考文章:
https://www.cnblogs.com/franknihao/p/6613236.html
https://docs.python.org/3/library/zipfile.html
https://docs.python.org/3/library/tarfile.html
轉載于:https://www.cnblogs.com/huzixia/p/10391724.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Python的压缩文件处理 zipfile tarfile的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 家人非常注重环保问题,想知道柏尔定制地板
- 下一篇: CF div2 PA 2019.02.1