简体   繁体   English

如何在Python中压缩文件夹及其所有文件,同时保留其内容的文件夹名称和相对路径?

[英]How to zip a folder and all of its files in Python, while preserving the folder name and relative paths for its contents?

I am trying to create a backup script in Python 3.5 that will zip all the contents of a specified folder. 我正在尝试在Python 3.5中创建一个备份脚本,该脚本将压缩指定文件夹的所有内容。 Here is what I am doing now: 这是我现在正在做的事情:

import shutil
import datetime
import os
import os.path

import dropbox


INPUT_FOLDER = '~/Documents/db-backup-test/'
ARCHIVE_PATH = '~/Documents/tmp/'
ARCHIVE_FILE_NAME = "db-backup_iOS__"


def compress_folder(origem, destino):
    try:
        arq = shutil.make_archive(destino, 'zip', root_dir=origem, base_dir=origem)
    except Exception as e:
        print('\n\nAn error was found during compression:')
        print(e)


timestamp = str(datetime.datetime.now())
input_path = os.path.expanduser(INPUT_FOLDER)
archive_path = os.path.expanduser(ARCHIVE_PATH + ARCHIVE_FILE_NAME + timestamp)

compress_folder(input_path, archive_path)

I goes well, except for one thing: the resulting zip archive extracts its contents with a reproduction of the full original path. 我做的很好,除了一件事:生成的zip存档提取了其内容,并复制了完整的原始路径。 What I would like is to get is a simple copy of the folder, with its original name and its contents with relative paths, when extracting the archive. 我想得到的是在提取档案时,该文件夹的简单副本及其原始名称和带有相对路径的内容。

I was looking into a simple and short solution that would not require to iterate through the folder contents. 我正在寻找一个简单且简短的解决方案,该解决方案不需要遍历文件夹内容。

Is this possible with shutil.make_archive() , or will I need to dig into other modules, like zipfile ? 是否可以使用shutil.make_archive() ,还是我需要深入研究其他模块,例如zipfile

Use the arcname parameter to control the name/path in the zip file. 使用arcname参数控制zip文件中的名称/路径。

#!/usr/bin/env python2.7

import os
import zipfile

def zip(src, dst):
   zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
   abs_src = os.path.abspath(src)
   for dirname, subdirs, files in os.walk(src):
       for filename in files:
          absname = os.path.abspath(os.path.join(dirname, filename))
          arcname = absname[len(abs_src) + 1:]
          print 'zipping %s as %s' % (os.path.join(dirname, filename), arcname)
          zf.write(absname, arcname)
   zf.close()
zip("src", "dst")

With a directory structure like this: 使用这样的目录结构:

src
└── a
    ├── b
    │   └── bar
    └── foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM