tarfile包中的.open(name, mode)方法能够以mode指定的方式打开name压缩文件,并返回一个TarFile类对象。调用TarFile对象的extractall(path)方法可以将tar文档解压到path指定的位置。
importtarfile tar=tarfile.open('*.tar.gz',mode="r:gz")#"r:gz"表示openforreadingwithgzipcompression tar.extractall(path='temp')###将tar.gz文件解压到temp文件夹下 tar.close()
open返回的对象不但可以用来读文档数据('r': reading),还可以写('w': writing),附加('a': appending)。
相关推荐:《Python教程》
如下是mode取值所对应的含义:
'r'or'r:*'openforreadingwithtransparentcompression 'r:'openforreadingexclusivelyuncompressed 'r:gz'openforreadingwithgzipcompression 'r:bz2'openforreadingwithbzip2compression 'r:xz'openforreadingwithlzmacompression 'a'or'a:'openforappending,creatingthefileifnecessary 'w'or'w:'openforwritingwithoutcompression 'w:gz'openforwritingwithgzipcompression 'w:bz2'openforwritingwithbzip2compression 'w:xz'openforwritingwithlzmacompression 'x'or'x:'createatarfileexclusivelywithoutcompression,raise anexceptionifthefileisalreadycreated 'x:gz'createagzipcompressedtarfile,raiseanexception ifthefileisalreadycreated 'x:bz2'createabzip2compressedtarfile,raiseanexception ifthefileisalreadycreated 'x:xz'createanlzmacompressedtarfile,raiseanexception ifthefileisalreadycreated 'r|*'openastreamoftarblockswithtransparentcompression 'r|'openanuncompressedstreamoftarblocksforreading 'r|gz'openagzipcompressedstreamoftarblocks 'r|bz2'openabzip2compressedstreamoftarblocks 'r|xz'openanlzmacompressedstreamoftarblocks 'w|'openanuncompressedstreamforwriting 'w|gz'openagzipcompressedstreamforwriting 'w|bz2'openabzip2compressedstreamforwriting 'w|xz'openanlzmacompressedstreamforwriting
下一篇