python生成tar文件内容的方法?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!

tarfile包中的.open(name, mode)方法能够以mode指定的方式打开name压缩文件,并返回一个TarFile类对象。调用TarFile对象的extractall(path)方法可以将tar文档解压到path指定的位置。

importtarfiletar=tarfile.open('*.tar.gz',mode="r:gz")#"r:gz"表示openforreadingwithgzipcompressiontar.extractall(path='temp')###将tar.gz文件解压到temp文件夹下tar.close()

open返回的对象不但可以用来读文档数据('r': reading),还可以写('w': writing),附加('a': appending)。

如下是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,raiseanexceptionifthefileisalreadycreated'x:gz'createagzipcompressedtarfile,raiseanexceptionifthefileisalreadycreated'x:bz2'createabzip2compressedtarfile,raiseanexceptionifthefileisalreadycreated'x:xz'createanlzmacompressedtarfile,raiseanexceptionifthefileisalreadycreated'r|*'openastreamoftarblockswithtransparentcompression'r|'openanuncompressedstreamoftarblocksforreading'r|gz'openagzipcompressedstreamoftarblocks'r|bz2'openabzip2compressedstreamoftarblocks'r|xz'openanlzmacompressedstreamoftarblocks'w|'openanuncompressedstreamforwriting'w|gz'openagzipcompressedstreamforwriting'w|bz2'openabzip2compressedstreamforwriting'w|xz'openanlzmacompressedstreamforwriting

感谢各位的阅读!看完上述内容,你们对python生成tar文件内容的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。