python標准庫之zipfile


python標准庫zipfile

什么是zip文件?為何在網絡上zip打包的文件比較常見?而不是rar?

zip是一種壓縮歸檔的文件,zip開源的。

python的zipfile模塊,有兩個主要的類

ZipFile()

函數,判斷是否為zip類型文件

zipfile. is_zipfile ( filename )

Returns True if filename is a valid ZIP file based on its magic number,otherwise returns False. filename may be a file or file-like object too


直接從壓縮文件中讀取文件內容
ZipFile. read ( name [, pwd ] )
# 實際上調用了self.open().read()

Return the bytes of the file name in the archive. name is the name of thefile in the archive


ZipFile. open ( name [, mode [, pwd ] ] )

Extract a member from the archive as a file-like object (ZipExtFile)


ZipFile. close ( )

Close the archive file. You must call close() before exiting your programor essential records will not be written.

ZipInfo()


# 壓縮到指定文件
def file_zip(src, dst):
    zip_obj = ZipFile(dst, mode='w')
    zip_obj.write(src)
    zip_obj.close()


 # 解壓縮
def unzip(src):
    zip_obj = ZipFile(src, mode='r')
    for info in zip_obj.filelist:
        zip_obj.extract(member=info)
    zip_obj.close()


zipfile的命令行接口

Usage:
    zipfile.py -l zipfile.zip        # Show listing of a zipfile
    zipfile.py -t zipfile.zip        # Test if a zipfile is valid
    zipfile.py -e zipfile.zip target # Extract zipfile into target dir
    zipfile.py -c zipfile.zip src ... # Create zipfile from sources

-c Create

-e Extract(提取)

-l List



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM