'Python - Maintain Folder Structures while Zipping
I've got an extremely specific use-case, where I've got multiple folders in a single directory, each of which as subfolders and files, so on and so forth. I need to be able to zip all of those top-level folders into the same archive, while preserving ALL folder / path structure.
For example, if the original folder structure was like this:
/topLevel
- /directory1
- /directory1_subfolder
- /subfolderOfSubfolder
-/file.txt
- /file.txt
- /directory1file.txt
- /directory2
- /directory2_subfolder
- /file.txt
- /directory2file.txt
I would want it to look EXACTLY like that in the zip archive.
I was using this code I modified from a different StackOverflow post, but it doesn't seem to work for my use-case:
archive = ZipFile('archive_name.zip', 'w')
try:
for folderName, subfolders, filenames in os.walk(PATH + "/assets"):
for filename in filenames:
#create complete filepath of file in directory
filePath = os.path.join(folderName, filename)
print(YELLOW + "BUILD: " + GREEN + filePath + RESET)
# Add file to zip
archive.write(filePath, basename(filePath))
for folderName, subfolders, filenames in os.walk(PATH + "/data"):
for filename in filenames:
#create complete filepath of file in directory
filePath = os.path.join(folderName, filename)
print(YELLOW + "BUILD: " + GREEN + filePath + RESET)
# Add file to zip
archive.write(filePath, basename(filePath))
for folderName, subfolders, filenames in os.walk(PATH + "/modules"):
for filename in filenames:
#create complete filepath of file in directory
filePath = os.path.join(folderName, filename)
print(YELLOW + "BUILD: " + GREEN + filePath + RESET)
# Add file to zip
archive.write(filePath, basename(filePath))
for folderName, subfolders, filenames in os.walk(PATH + "/scripts"):
for filename in filenames:
#create complete filepath of file in directory
filePath = os.path.join(folderName, filename)
print(YELLOW + "BUILD: " + GREEN + filePath + RESET)
# Add file to zip
archive.write(filePath, basename(filePath))
for folderName, subfolders, filenames in os.walk(PATH + "/settings"):
for filename in filenames:
#create complete filepath of file in directory
filePath = os.path.join(folderName, filename)
print(YELLOW + "BUILD: " + GREEN + filePath + RESET)
# Add file to zip
archive.write(filePath, basename(filePath))
except Exception as err:
print(YELLOW + "BUILD:" + RED + " <ERROR> " + SPECIALDRIVE + str(err) + RESET)
It just jumbles all of the files together like this
Print output looks correct, for the most part.
Does anyone have any suggestions on how I can get Python to maintain my folder's structures? Thanks in advance!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|