標籤:

Python標準庫系列之tarfile模塊

The tarfile module makes it possible to read and write tar archives, including those using gzip, bz2 and lzma compression. Use the zipfile module to read or write .zip files, or the higher-level functions in shutil.

官方文檔:docs.python.org/3.5/lib

打包及重命名文件

>>> import tarfile # 以w模式創建文件>>> tar = tarfile.open(tar_file.tar,w) # 添加一個文件,arcname可以重命名文件 >>> tar.add(/tmp/folder/file.txt, arcname=file.log) # 添加一個目錄>>> tar.add(/tmp/folder/tmp) # 關閉 >>> tar.close()

查看文件列表

>>> tar = tarfile.open(tar_file.tar,r) # 獲取包內的所有文件列表 >>> tar.getmembers() [<TarInfo file.log at 0x7f737af2da70>, <TarInfo tmp/folder/tmp at 0x7f737af2dd90>]

追加

# 以w模式創建文件 >>> tar = tarfile.open(tar_file.tar,a) >>> tar.add(/tmp/folder/sc.pyc) >>> tar.close() >>> tar = tarfile.open(tar_file.tar,r) >>> tar.getmembers() [<TarInfo file.log at 0x7ff8d4fa1110>, <TarInfo tmp/folder/tmp at 0x7ff8d4fa11d8>, <TarInfo tmp/folder/sc.pyc at 0x7ff8d4fa12a0>]

解壓全部文件

>>> import os >>> import tarfile >>> os.system("ls -l") 總用量 12 -rw-rw-r-- 1 ansheng ansheng 10240 5月 26 17:40 tar_file.tar 0 >>> tar = tarfile.open(tar_file.tar,r) >>> tar.extractall() >>> tar.close() >>> os.system("ls -l") 總用量 16 -rw-rw-r-- 1 ansheng ansheng 0 5月 26 16:05 file.log -rw-rw-r-- 1 ansheng ansheng 10240 5月 26 17:40 tar_file.tar drwxrwxr-x 3 ansheng ansheng 4096 5月 26 17:48 tmp 0

解壓單個文件

如果我們的壓縮包很大的情況下,就不能夠一次性解壓了,那樣太耗內存了,可以通過下面的方式進行解壓,其原理就是一個文件一個文件的解壓。

import tarfile tar = tarfile.open(tar_file.tar,r) for n in tar.getmembers(): tar.extract(n,"/tmp") tar.close()

推薦閱讀:

Tkinter中的mainloop應該如何理解?
Python 中的作用域準則
ElasticSearch + xpack 使用

TAG:Python |