- 1 year ago
What's the easiest way to recursively zip files within a directory that starts with the same name?
To recursively zip files within a directory that starts with the same name, you can use a scripting language like Python. Here's an example using Python's zipfile
module:
pythonimport os
import zipfile
def zip_files_with_same_name(directory):
for root, dirs, files in os.walk(directory):
# Check if the directory name starts with the same name
if os.path.basename(root).startswith(os.path.basename(directory)):
zip_file_path = os.path.join(root, os.path.basename(root) + '.zip')
with zipfile.ZipFile(zip_file_path, 'w') as zipf:
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path, arcname=os.path.relpath(file_path, directory))
# Usage
directory_path = '/path/to/directory'
zip_files_with_same_name(directory_path)
In this example, the zip_files_with_same_name()
function recursively walks through the directory and its subdirectories using os.walk()
. It checks if the directory name starts with the same name as the provided directory.
For each matching directory, a new zip file is created with the directory's name plus the .zip
extension. The function then iterates over the files within the directory and adds them to the corresponding zip file using zipfile.ZipFile.write()
. The arcname
parameter is used to preserve the relative path structure within the zip file.
To use this code, replace /path/to/directory
with the actual path of the directory you want to zip. Running the script will create zip files for each directory that starts with the same name.
Please note that this example uses Python's built-in zipfile
module, so ensure that you have Python installed on your system.