#!/usr/bin/env /usr/local/bin/python
# encoding: utf-8
import tarfile
import os
import time
start = time.time()
tar=tarfile.open('/path/to/your.tar,'w')
for root,dir,files in os.walk('/path/to/dir/'):
for file in files:
fullpath=os.path.join(root,file)
tar.add(fullpath,arcname=file)
tar.close()
print time.time()-start
在打包的过程中可以设置压缩规则,如想要以gz压缩的格式打包
tar=tarfile.open('/path/to/your.tar.gz','w:gz')
其他格式如下表:
tarfile.open的mode有很多种:
mode
action
'r' or 'r:*'
Open for reading with transparent compression (recommended).
'r:'
Open for reading exclusively without compression.
'r:gz'
Open for reading with gzip compression.
'r:bz2'
Open for reading with bzip2 compression.
'a' or 'a:'
Open for appending with no compression. The file is created if it does not exist.