最近项目上有一个ftp上传程序,需要把碎文件打包上传,到服务端再解包。本来已经只能通过shell来搞这个了,无奈打包过程中有一部分业务逻辑,不能把整个目录都打包,惊喜地发现python有tarfile这个东西,太惊喜了,试用完后发现还挺不错,打包一组466M的文件,共778个文件花了1.9s,解包花了2.3s。打包,解包代码如下:
tar打包
在写打包代码的过程中,使用tar.add()增加文件时,会把文件本身的路径也加进去,加上arcname就能根据自己的命名规则将文件加入tar包
打包代码:
#!/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. |
'w' or 'w:' | Open for uncompressed writing. |
'w:gz' | Open for gzip compressed writing. |
'w:bz2' | Open for bzip2 compressed writing. |
tar解包
tar解包也可以根据不同压缩格式来解压。
#!/usr/bin/env /usr/local/bin/python
# encoding: utf-8
import tarfile
import time
start = time.time()
t = tarfile.open("/path/to/your.tar", "r:")
t.extractall(path = '/path/to/extractdir/')
t.close()
print time.time()-start
上面的代码是解压所有的,也可以挨个起做不同的处理,但要如果tar包内文件过多,小心内存哦~
tar = tarfile.open(filename, 'r:gz')
for tar_info in tar:
file = tar.extractfile(tar_info)
do_something_with(file)