1、通常来说,在工作中我们遇到的最多的压缩文件格式只有5种,如下:
xxx.gz
、
xxx.tar
、
xxx.tgz
、
xxx.zip
、
xxx.rar
2、各种压缩文件格式的简介:
①gz: 即gzip压缩方式,通常只能压缩一个文件。与tar结合起来就可以实现先打包,再压缩。
②tar: linux系统下的打包工具,只打包,不压缩。
③tgz: 即tar.gz,先用tar打包,然后再用gz压缩得到的文件。
④zip: 不同于gzip,虽然使用相似的算法,可以打包压缩多个文件,不过分别压缩文件,压缩率低于tar。
⑤rar: 打包压缩文件,最初用于DOS,基于window操作系统。压缩率比zip高,但速度慢,随机访问的速度也慢。
3、其实
tarfile
模块的使用和文件操作非常相似,只是在压缩模式上略有不同。
4、在Linux操作系统中,tar只是Linux操作系统的一种打包归档方式,打包成为tar包之后,才可以使用其它的压缩程序去压缩。其中,最常用的压缩方式是gzip,压缩率最高的方式bzip2,此外还支持另一种比较小众的xzip格式。
5、
os.system(cmd)
可以使Python脚本执行命令,当然包括:tar -czf *.tar.gz *,tar -xzf *.tar.gz,unzip等,这样同样可以解决创建压缩包以及解压等问题。
tarfile的语法格式
1、打开/创建压缩包
tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)
①name:打开的文件名或者路径
②bufsize:用于指定数据块的大小,默认为20*512字节
③mode:文件打开模式,默认为‘r’;tarfile模块的打开模式有如下:
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.(采用gzip格式解压并打开文件)
'r:bz2' Open for reading with bzip2 compression.(采用bz2格式解压并打开文件)
'r:xz' Open for reading with lzma compression.(采用lzma格式解压并打开文件)
'x'or 'x:' Create a tarfile exclusively without compression. Raise an [FileExistsError]exception if it already exists.(仅创建打包文件,不压缩)
'x:gz' Create a tarfile with gzip compression. Raise an [FileExistsError]exception if it already exists.(采用gzip方式压缩并打包文件)
'x:bz2' Create a tarfile with bzip2 compression. Raise an [FileExistsError]exception if it already exists.(采用bzip2方式压缩并打包文件)
'x:xz' Create a tarfile with lzma compression. Raise an [FileExistsError]exception if it already exists.(采用lzma方式压缩并打包文件)
'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.(以gzip的方式压缩并写入)
'w:bz2' Open for bzip2 compressed writing.(以bzip2的方式压缩并写入)
'w:xz' Open for lzma compressed writing.(以lzma的方式压缩并写入)
注意:如果当前模式不能正常打开文件用于读取,将抛出
ReadError
异常,这种情况下,请使用“r”模式。如果指定的压缩方式不支持,将抛出
CompressionError
异常。
在
w:gz
,
r:gz
,
w:bz2
,
r:bz2
,
x:gz
,
x:bz2打开
模式下,
tarfile.open()
方法额外接受一个压缩等级参数
compresslevel
,默认值为9。
import tarfile
# tar包以gzip格式压缩
with tarfile.open('test.tar.gz', 'w:gz') as tf:
tf.add('test.tar')
2、压缩包中添加文件
压缩文件的方式主要是将模式改变,在rwx的基础上加上各个压缩的方式,变成:r:gz、w:bz2、x:xz等样式。
add(name, arcname)
①name:压缩文件文件名或者文件路径
②arcname:压缩文件文件名的别名(可以省略该参数)(注意:压缩别名一定不要以路径分隔符为结尾,否则只会创建一个文件夹)
import tarfile
with tarfile.open('test.tar', 'w') as tf:
tf.add('test.txt')
3、解压缩
1、将一些文件归档压缩为.tar.gz压缩文件
import os
import tarfile
print(os.getcwd())
print(os.listdir())
# 创建压缩包(此时没有add任何文件到压缩包中,所以执行完成后只是一个空压缩包)
tar = tarfile.open("tartest.tar.gz", "w:gz")
# 创建压缩包
tar.add("1.py")
tar.add("2.py")
tar.add("3.py")
tar.add("4.py")
tar.add("5.py")
# 关闭tar文件对象
tar.close()
运行结果:
https://www.liujiangblog.com/course/python/63
https://www.jianshu.com/p/cbba3e2dbdcd
去期待陌生,去拥抱惊喜。