scoots
scoots

Reputation: 294

Preserve file structure with shutil.make_archive

Is there a way to exclude a zip file from opening into its own directory? I'm trying to zip a directory using shutil.make_archive with the following file structure:

dir
\-- python
    \-- files

Currently, I zip it, in the python directory:

    shutil.make_archive(zip_name, "zip", os.getcwd())

This gives me a zip_name.zip file. When I unzip it, I want it to be unzip to its original file structure, excluding the directory with the file name. I get:

zip_name
\-- python
    \-- files

but I want:

python
    \-- files

Is there a way to do this with shutil or should I be using Zipfile instead? Thanks for looking.

Upvotes: 1

Views: 632

Answers (1)

scoots
scoots

Reputation: 294

I wasn't able to figure out how to make it work with shutil, although my friend pointed out that I could probably do it with relative paths. Thought I'd post my answer here for anyone else looking for an answer. I turned to ZipFile, and came up with this:

    with zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED) as new_zip:
    src_path = os.getcwd()
    for root, dirs, files in os.walk(src_path):
        for file in files:
            file_path = os.path.join(root, file)
            archive_file_path = os.path.relpath(file_path, src_path)
            new_zip.write(file_path, os.path.join("python/", archive_file_path))

While a little hacky, it works. It preserves the file structure and unzips directly into the python/ directory instead of the zip_name directory.

Upvotes: 1

Related Questions