ubuntu 中导 tarfile,win 不亲切
2021-05-17 05:30
标签:bin 绝对路径 功能 scm mes list sys size err ubuntu 中导 tarfile,win 不亲切 标签:bin 绝对路径 功能 scm mes list sys size err 原文地址:https://www.cnblogs.com/max404/p/11785061.html# ### tarfile 压缩模块 后缀为.tar | .tar.gz | .tar.bz2
import tarfile
tarfile在win中功能不全,肾用,熬夜bug
# ### 1.创建tar压缩包 [官方: 理论上可以压缩到最小的模式是bz2]
# (1) 创建压缩包
""".tar的压缩包,只打包不压缩 276480"""
tf = tarfile.open("ceshi1029.tar","w",encoding="utf-8")
# (2) 写入文件到压缩包中
tf.add("/bin/ntfscmp","ntfscmp")
tf.add("/bin/openvt","openvt")
tf.add("/bin/grep","tmp/grep")
# (3) 关闭压缩包
tf.close()
# 2.创建.tar.gz压缩包 120462
tf = tarfile.open("ceshi1030.tar.gz","w:gz",encoding="utf-8")
tf.add("/bin/ntfscmp","ntfscmp")
tf.add("/bin/openvt","openvt")
tf.add("/bin/grep","tmp/grep")
tf.close()
# 3.创建.tar.bz2压缩包 115728
tf = tarfile.open("ceshi1031.tar.bz2","w:bz2",encoding="utf-8")
tf.add("/bin/ntfscmp","ntfscmp")
tf.add("/bin/openvt","openvt")
tf.add("/bin/grep","tmp/grep")
tf.close()
# ### 2.解压压缩包
tf = tarfile.open("ceshi1030.tar.gz","r",encoding="utf-8")
# extract(文件,路径)
# tf.extract("ntfscmp","ceshi1030")
# extractall(路径)
tf.extractall("ceshi1030")
tf.close()
# ### 3.追加文件 支持with语法
with tarfile.open("ceshi1029.tar","a",encoding="utf-8") as tf :
tf.add("/bin/gzip","gzip")
# error tarfile中的追加,只能是对只打包不压缩的包进行追加,其他的模式不可以;
"""
with tarfile.open("ceshi1031.tar.bz2","a",encoding="utf-8") as tf:
tf.add("/bin/gzip","gzip")
"""
# ### 4.查看压缩包中的内容
with tarfile.open("ceshi1029.tar","r",encoding="utf-8") as tf :
lst = tf.getnames()
print(lst)
# ### 如何解决tarfile中存在的缺陷?(不能追加文件到已经压缩的包)
"""
(1) 先解压所有文件到文件夹
(2) 把想要追加的内容复制到文件夹中
(3) 经过过滤筛选,重新打包压缩
"""
import os
# 获取当前脚本所在的路径
pathvar = os.getcwd()
# print(res) # /mnt/hgfs/gongxiang8/day16
# 压缩包路径
path1 = os.path.join(pathvar,"ceshi1031.tar.bz2")
print(path1)
# 解压的路径
path2 = os.path.join(pathvar,"ceshi1031")
# (1) 先解压所有文件到文件夹
with tarfile.open( path1 , "r",encoding="utf-8") as tf:
tf.extractall(path2)
# (2) 把想要追加的内容复制到文件夹中
mybin = "cp -a /bin/ip " + path2 # cp -a /bin/ip /mnt/hgfs/gongxiang8/day16/ceshi1031
os.system(mybin)
# (3) 经过过滤筛选,重新打包压缩
lst = os.listdir(path2)
print(lst)
with tarfile.open(path1,"w:bz2",encoding="utf-8") as tf:
for i in lst:
if i != "openvt":
# 拼接绝对路径
pathnew = os.path.join(path2,i)
# add(路径,别名)
tf.add(pathnew,i)
上一篇:AcWing 803. 区间合并
文章标题:ubuntu 中导 tarfile,win 不亲切
文章链接:http://soscw.com/index.php/essay/86588.html