Python tarfile路径问题

Python tarfile路径问题

存在问题

假设在目录test1/test2下有两个文件a.txtb.txt

test1
  |--test2
  |    |--a.txt
  |    |--b.txt
  |--test3
  |--test4
  		

现在需要将其压缩至test1/test3目录下

很容易得到

def tar_files(file_name, from_path, to_path):
    tar_file = file_name + '.tar.gz'
    if not os.path.exists(to_path):
        os.makedirs(to_path)
    tar = tarfile.open(os.path.join(to_path, tar_file), 'w:gz')
    
    
    files = [os.path.join(from_path, item) for item in os.listdir(from_path) if os.path.isfile(os.path.join(from_path, item))]
    # print(files)

    for file in files:
        tar.add(file)
    tar.close()
    
    
def tar_extract(file_name, from_path, to_path):
    tar = tarfile.open(os.path.join(from_path, file_name), 'r:gz')
    if not os.path.exists(to_path):
        os.makedirs(to_path)

    for file in tar.getnames():
        tar.extract(file, to_path)
    
    tar.close()    

压缩

tar_files('mytar', 'test1/test2', 'test1/test3')

然后将压缩文件解压至test1/test4目录

tar_extract('mytar.tar.gz', 'test1/test3', 'test1/test4')

那么问题来了

原本以为test4目录下直接是a.txtb.txt文件

结果发现解压后的两个文件保留了原有目录路径

即,在test4目录下解压成了test1/test2/a.txttest1/test2/b.txt

而不是单纯的两个文件

解决方案

经测试,这两个文件路径与代码中tar.add(file)中的file的文件路径是一致的

那么只需要确保file中的路径只为文件,不包含其所在目录就行了

这时就需要os.chdir()来切换工作目录

切换至需要压缩的文件的目录下

添加了一些功能

def tar_files(file_name, from_path, to_path, delete=False):
    '''
    打包压缩一个目录下的文件
    file_name: 生成的tar文件名,不需要有.tar.gz
    from_path: 将from_path目录下的文件打包压缩
    to_path: 将tar文件放在to_path目录下
    delete: 是否删除from_path下的文件,默认False
    '''
    tar_file = file_name + '.tar.gz'
    if not os.path.exists(to_path):
        os.makedirs(to_path)
    tar = tarfile.open(os.path.join(to_path, tar_file), 'w:gz')
    # 记录当前工作目录
    cur_path = os.getcwd()
    # 切换目录
    os.chdir(from_path)
    
    files = [item for item in os.listdir('.') if os.path.isfile(item)]

    for file in files:
        tar.add(file)
    tar.close()
    
    if delete:
        for file in files:
            os.remove(file)
    # 切换回原来工作目录        
    os.chdir(cur_path)
            
def tar_extract(file_name, from_path, to_path, delete=False):
    '''
    将压缩文件中的文件提取出来
    file_name: 对应压缩文件  XXX.tar.gz
    from_path: 压缩文件所在目录
    to_path: 将文件提取至to_path目录
    delete: 是否删除该压缩文件,默认False
    '''
    tar = tarfile.open(os.path.join(from_path, file_name), 'r:gz')
    if not os.path.exists(to_path):
        os.makedirs(to_path)
        
    for file in tar.getnames():
        tar.extract(file, to_path)
    
    tar.close()
    
    if delete:
        os.remove(os.path.join(from_path, file_name))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值