python模块整理6-tarfile模块

官方文档:http://docs.python.org/library/tarfile.html#module-tarfile

一、打包
制作文件
>>> statement="This is a big line that ........"
>>> with open('/root/largeFile.txt','w') as myfile:
... for x in xrange(20000):
... x+=1
... myfile.write("%s\n" % statement )
1、打包文件
>>> tar=tarfile.open('/root/largeFile.txt.tar','w')
>>> tar.add('/root/largeFile.txt')
>>> tar.close()
2、打包目录
>>> tar=tarfile.open('temp.tar','w')
>>> tar.add('/tmp')
>>> tar.close()
os.walk遍历打包的目录
tar=tarfile.open('temp_walk.tar','w')
for root.dir,files in os.walk('tmp'):
for file in files:
fullpath=os.path.join(root,file)
tar.add(fullpath)
tar.close()
二、压缩
1、bz2压缩
tar=tarfile.open("largefile.tz2","w|bz2")
tar.add('largeFile.txt')
>>>tar.close()
# tar -jtvf largefile.tz2
-rw-r--r-- 0 root wheel 655360 Mar 14 22:21 largeFile.txt
2、gzip压缩
>>>tar=tarfile.open("tmpdir.tgz","w|gz")
>>>tar.add('/tmp')
>>>tar.close()
#tar -ztvf tmpdir.tgz
三、检查tar文件的内容
>>>import tarfile
>>>tar=tarfile.open('largefile.tar','r')
>>>tar.list()
-rw-r--r-- root/wheel 655360 2012-03-14 22:21:18 largeFile.txt
>>>tar.name
'/root/largefile.tar'
>>>tar.getnames() 返回只显示名字不显示其他信息的列表
>>>tar.members
[<TarInfo 'largeFile.txt' at 0x2976be6c>]

bz2压缩的
>>>tar=tarfile.open('tmpdir2.tz2','r|bz2')
>>>tar.list()
xr-xr-x root/wheel 916 2012-03-14 21:54:01 tmp/sync_dir_A/bgfsck
-r-xr-xr-x root/wheel 9401 2012-03-14 21:54:01 tmp/sync_dir_A/bluetooth
>>>tar.name
'/root/tmpdir2.tz2
>>>tar.getnames() 返回只显示名字不显示其他信息的列表
'tmp/sync_dir_A/ypupdated',
>>>tar.members
[<TarInfo 'tmp' at 0x29717cec>,
<TarInfo 'tmp/.snap' at 0x29717a2c>,
<TarInfo 'tmp/.X11-unix' at 0x29717b2c>,
<TarInfo 'tmp/.XIM-unix' at 0x2971c06c>,

gzip压缩的
>>>tar=tarfile.open('tmpdir1.tgz','r|gz')
>>>tar.list()
-rwxrwxrwt root/wheel 0 2012-03-14 21:54:05 tmp/
-rwxrwxr-x root/operator 0 2012-03-10 20:17:46 tmp/.snap/
>>> tar.name
'/root/tmpdir1.tgz'
>>> tar.getnames()
['tmp',
'tmp/.snap',
'tmp/.X11-unix',
'tmp/.XIM-unix',
'tmp/.ICE-unix',
'tmp/.font-unix',
'tmp/python.data',
'tmp/aprHZAuuw',
>>> tar.members
[<TarInfo 'tmp' at 0x28e3852c>,
<TarInfo 'tmp/.snap' at 0x28e382ec>,
<TarInfo 'tmp/.X11-unix' at 0x28e382

四、解压缩 tar.extractall()
>>> import os
>>> import tarfile
>>> os.getcwd()
'/tmp'
>>> os.chdir('/root')
>>> os.mkdir('/root/tar_tempdir')
>>> os.chdir('/root/tar_tempdir')
>>> tar=tarfile.open('/root/tmpdir1.tgz','r|gz')
>>> tar.extractall()
>>> tar.close()
>>> os.listdir(".")
['tmp']
>>> os.listdir("./tmp")
['.snap', '.X11-unix', '.XIM-unix', '.ICE-unix', '.font-unix', 'python.data', 'aprHZAuuw', 'mpmtx13970', 'mpmtx13971', 'mpmtx13972', 'mpmtx13973', 'mpmtx13974', 'mpmtx13975', 'mpmtx13976', 'mpmtx13977', 'Shell2.sh', 'file.txt', 'gdchart0.11.5dev.tar.gz', 'gdchart0.11.5dev', 'pygdchart2_0.beta1.orig.tar.gz', 'pygdchart2alpha2', 'rootdir', 'testfile2', 'pygdchart2_0.beta1-3.4.diff', 'os_rename', 'file1', 'TSFILE', 'test_mv', 'file2', 'file3', 'dir1', 'dir2', 'sync_dir_B', 'sync_dir_A']

 

posted on 2012-10-04 11:38  @Jin  阅读(1704)  评论(0编辑  收藏  举报

导航