使用Python管理壓縮包

2021-09-07 18:56:21 字數 2121 閱讀 8004

一、 使用tarfile庫讀取與建立tar包

1. 建立tar包

in [1]: import tarfile

in [2]: with tarfile.open('demo.tar',mode='w') as out:

...: out.add('1.txt')

...: out.add('2.txt')

...:

2. 讀取tar包

in [1]: import tarfile

in [2]: with tarfile.open('demo.tar') as t:

...: for file in t.getmembers():

...: print(file.name)

...:

1.txt

2.txt

3. 建立壓縮包

in [8]: with tarfile.open('demo.tar.gz',mode='w:gz') as out:

...: out.add('1.txt')

...: out.add('2.txt')

4. 讀取壓縮包

in [10]: with tarfile.open('demo.tar.gz',mode='r:gz') as out:

...: for f in out.getmembers():

...: print(f.name)

...:

1.txt

2.txt

5. 提取單個或者所有檔案

in [14]: with tarfile.open('demo.tar.gz',mode='r:gz') as out:

...: out.extract('1.txt')

...:

in [15]: with tarfile.open('demo.tar.gz',mode='r:gz') as out:

...: out.extractall()

...:

二、使用zipfile庫建立和讀取壓縮包

1. 建立zip檔案

in [19]: import zipfile

in [20]: newzip = zipfile.zipfile('demo.zip','w')

in [21]: newzip.write('1.txt')

in [22]: newzip.write('2.txt')

in [23]: newzip.close()

2. 讀取zip檔案

in [24]: newzip = zipfile.zipfile('demo.zip')

in [25]: newzip.namelist()

out[25]: ['1.txt', '2.txt']

3. 解壓zip檔案

in [27]: newzip.extract('1.txt')

out[27]: '/tmp/test/1.txt'

in [28]: newzip.extractall()

三、 使用shutil管理壓縮包

in [40]: import shutil

in [41]: shutil.make_archive('demo','zip')

out[41]: 'demo.zip'

in [42]: shutil.make_archive('demo','gztar')

out[42]: 'demo.tar.gz'

in [43]: shutil.unpack_archive('demo.tar.gz')

in [44]: shutil.unpack_archive('demo.zip')

使用Python管理壓縮包

一 使用tarfile庫讀取與建立tar包 1.建立tar包 in 1 import tarfile in 2 with tarfile.open demo.tar mode w as out out.add 1.txt out.add 2.txt 2.讀取tar包 in 1 import tarf...

php生成壓縮包和開啟壓縮包

需呀用到ziparchive類,php預設帶的有,廢話不說,直接上 親測可以使用,先來個生成壓縮包,解壓縮包後邊補上 開啟php支援ziparchive 在php.ini檔案中將extension php zip.dll 開頭的 的去掉,重啟www伺服器就可以了 1 對多個檔案生成壓縮包 生成壓縮檔...

使用ant解壓縮包 打壓縮包

需要用到的jar包 ant.jar 1 解壓縮包 解壓指定zip檔案 param unzipfile 需要解壓縮的壓縮包路徑 路徑 名稱 字尾名 param destfile 解壓到的目錄 public void uncompress file unzipfile,file destfile els...