python~module gzip 使用方法,及簡介! 附件 python ~ os 模組!!!__python

來源:互聯網
上載者:User
這個模組提供了一些簡單的介面來對檔案進行壓縮和解壓縮
類似於GNU項目的gzip和gunzip,資料的壓縮源於zlib模組的支援。
gzip.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)
開啟一個gzip已經壓縮好的gzip格式的檔案,並返回一個檔案對象:file object.
參數filename可以是真是的檔案名稱(a str or bytes對象),或著是已經存在的讀寫檔案對象。
參數mode在操作二進位的時候使用:'r','rb','a','ab','wb'
操作text的時候使用:'rt,'at','wt'
預設是:'rb'
參數compresslevel是0-9的數值
 
如何讀取壓縮檔import gzipwith gzip.open('/home/joe/file.txt.gz', 'rb') as f:    file_content = f.read()
如何建立一個gzip檔案import gzipcontent = b"Lots of content here"with gzip.open('/home/joe/file.txt.gz', 'wb') as f:    f.write(content)
如何gzip一個已存在的檔案(把已有檔案轉換成gzip格式)import gzipimport shutilwith open('/home/joe/file.txt', 'rb') as f_in:    with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:        shutil.copyfileobj(f_in, f_out)
如何gzip壓縮一個二進位字元
import gzips_in = b"Lots of content here"s_out = gzip.compress(s_in)
 
使用gzip模組壓縮檔
>>> import gzip #匯入python gzip模組,注意名字為全小

>>> g = gzip.GzipFile(filename="", mode="wb", compresslevel=9, fileobj=open('sitemap.log.gz', 'wb'))

>>> g.write(open('d:\\test\\sitemap.xml').read())

>>> g.close()

其中,filename參數是壓縮檔內,檔案的名字,為空白也可以,不修改

fileobj是產生的壓縮檔對象,它的路徑名稱等。

最後是把檔案寫入gzip檔案中去,再關閉操作串連。

filename = 'd:........' whatever ,例如:'d:\\test\\sitemap.log.gz'

使用gzip模組解壓縮檔案

>>> g = gzip.GzipFile(mode="rb", fileobj=open('d:\\test\\sitemap.log.gz', 'rb')) # python gzip 解壓

>>> open(r"d:\\haha.xml", "wb").write(g.read())

使用的時候注意,函數方法的大小寫一點要看仔細

如果gzip檔案是這種形式的:*.tar.gz,證明先是由tar命令壓縮後

後再由 gzip壓縮的需要先用解壓縮tar檔案,再用gzip模組解壓縮

其實,現在很多網頁為了提高瀏覽器端使用者的訪問速度,和搜尋引擎爬蟲抓取的速度,都在使用gzip壓縮。


還不清楚看 這裡。            或者這裡。
os模組看 這裡

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.