3

I want to archive only some files in my directory. Suppose that the following directory structure:

current_dir
  - current_file
    audio/
  - fileA
  - fileB

In this case, can I archive only audio/ and fileA from the Python script (current_file)?

I use shutil but the following command seems to use all the files in a specific directory.

shutil.make_archive("new_file", 'zip', dir_name)
Blaszard
  • 30,954
  • 51
  • 153
  • 233

1 Answers1

1

Here's a possible way to achieve what you want:

import os
import zipfile
import glob

content = [
    "audio",
    "fileA"
]


def zip_dir(path, zip_file):
    for root, dirs, files in os.walk(path):
        for file in files:
            zip_file.write(os.path.join(root, file))

zip_file = zipfile.ZipFile("mcve.zip", 'w')
for path in content:
    if os.path.isdir(path):
        zip_dir(path, zip_file)
    else:
        zip_file.write(path)
zip_file.close()
BPL
  • 9,632
  • 9
  • 59
  • 117