python tar 多目录压缩脚本,使用tarfile(Python)只压缩给定目录中的文件

我已经编写了以下脚本,它允许我将src(可以是单个文件或目录)压缩到目标'dst':#!/usr/bin/env python2

import tarfile

from ntpath import basename, dirname

from os import path, listdir, makedirs, chdir

import errno

import sys

class Archivator:

@staticmethod

def compress(src='input/test', dst='output'):

# if not path.isfile(src_file):

# print('Expecting absolute path to file (not directory) as "src". If "src" does contain a file, the file does not exist')

# return False

if not path.isdir(dst):

return False

# try:

# makedirs(dst_dir)

# except OSError as err:

# if err.errno != errno.EEXIST:

# return False

filename = basename(src) if path.isdir(src) else src

tar_file = dst + '/' + filename + '.tar.gz'

print(tar_file)

print(src)

with tarfile.open(tar_file, 'w:gz') as tar:

print('Creating archive "' + tar_file + '"')

# chdir(dirname(dst_dir))

recr = path.isdir(src)

if recr:

print('Source is a directory. Will compress all contents using recursion')

tar.add(src, recursive=recr)

return True

if __name__ == '__main__':

import argparse

parser = argparse.ArgumentParser(description='Uses tar to compress file')

parser.add_argument('-src', '--source', type=str,

help='Absolute path to file (not directory) that will be compressed')

parser.add_argument('-dst', '--destination', type=str, default='output/',

help='Path to output directory. Create archive inside the directory will have the same name as value of "--src" argument')

# Generate configuration

config = parser.parse_args()

Archivator.compress(config.source, config.destination)

对于单个文件,到目前为止我还没有遇到问题。然而,尽管src(作为一个目录)的压缩确实有效(递归和所有),但我注意到一个非常恼人的问题,即完整的目录结构被复制到tar.gz归档文件中。在

示例:

假设我有以下文件结构:

^{pr2}$

使用src = 'updates/package1'和{}我希望得到的归档文件将放在dst内(这行得通)

包含file1和file2

关于第二点./

|---compression.py (script above)

|

|---updates/

| |

| |---package1/

| |

| |---file1

| |---file2

| |---dir/

| |

| |---file3

|

|---compressed/

|

|---package1.tar.gz

|

|---file1

|---file2

|---dir/

|

|---file3

但是我得到了./

|---compression.py (script above)

|

|---updates/

| |

| |---package1/

| |

| |---file1

| |---file2

| |---dir/

| |

| |---file3

|

|---compressed/

|

|---package1.tar.gz

|

|---updates/

|

|---package1/

|

|---file1

|---file2

|---dir/

|

|---file3

我可能无法找到解决方案。我甚至在src(如果是一个目录)中尝试了chdir-ing,但是没有成功。我的一些实验甚至导致了OSError(由于缺少它应该存在的目录)和一个损坏的存档。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值