【发布时间】:2018-03-02 08:07:50
【问题描述】:
我编写了以下脚本,允许我将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 存档中复制。
例子:
假设我有以下文件结构:
./
|---compression.py (script above)
|
|---updates/
| |
| |---package1/
| |
| |---file1
| |---file2
| |---dir/
| |
| |---file3
|
|---compressed/
src = 'updates/package1' 和 dst = 'compressed' 我希望生成的存档将
- 被放置在
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(由于缺少预期存在的目录)和损坏的存档。
【问题讨论】:
标签: python python-2.7 filesystems compression tar