I have the following directory structure:
Directory1
|- SubDir1
| |- SubSubDir1
| |- file1.txt
| |- file2.txt
| |-SubSubDir2
| |- file1.txt
| |- file2.txt
|-SubDir2
| |- SubSubDir1
| |- file1.txt
| |- file2.txt
| |-SubSubDir2
| |- file1.txt
| |- file2.txt
Data files are inside SubSubDir, no exceptions.
I need to zip only certain files inside this directory with a given prefix, and I need the zip file of just these files to be parked in the same location as the data files using the name of the SubSubDir.
Basically like this:
Main_Directory
|- SubDir1
| |- SubSubDir1
| |- SubSubDir1.zip
| |- file1.txt
| |- file2.txt
| |-SubSubDir2
| |- SubSubDir2.zip
| |- file1.txt
| |- file2.txt
|-SubDir2
| |- SubSubDir1
| |- SubSubDir1.zip
| |- file1.txt
| |- file2.txt
| |-SubSubDir2
| |- SubSubDir2.zip
| |- file1.txt
| |- file2.txt
I have followed this, Create zip from directory using Python, and this, How can I only ZIP certain types of files in Python?.
This is the code, modified from the two references above, which navigates thru the folders and creates one Zip file at the top level for the files with a certain prefix:
import os, zipfile
name = 'D:/Power/Power_Data'
zip_name = name + '.zip'
with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED, allowZip64 = True) as zip_ref:
for folder_name, subfolders, filenames in os.walk(name):
print(folder_name)
print(subfolders)
for filename in filenames:
if filename.startswith('Prefix'):
file_path = os.path.join(folder_name, filename)
print(file_path)
zip_ref.write(file_path, arcname=os.path.relpath(file_path, name))
zip_ref.close()
I changed the code to run the for loop and use the folder names as the new zip file names, but the zip files though they have the correct name, are in the wrong place (they are at the location where the script is located), and are empty.
for folder_name, subfolders, filenames in os.walk(name):
for subfolder in subfolders:
name = subfolder
zip_name = subfolder + '.zip'
with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED, allowZip64 = True) as zip_ref:
for filename in filenames:
if filename.startswith('Prefix'):
zip_ref.write(name)
Tips are appreciated.