Basically I need to copy all files of a certain type within a folder into a ZipFile
at the highest level (so not within a folder).
For example I have a folder, 'A Folder' and within that folder are a load of .png files. I want to copy all those files into an existing ZipFile
. Currently I can only get the Folder to copy as well, so I end up with 'ZipFile\A Folder\lots of .pngs'
rather than 'ZipFile\lots of .pngs'
The code I'm using to move the files and folder is:
for root, dirs, files in os.walk('A Folder'):
for f in files:
fname = os.path.join(root, f)
myzip.write(fname)
Another quick thing, how would you go about deleting a folder from within a ZipFile
?开发者_如何学Python
According to the python docs, the zipfile.write() method supports a second argument that is the destination name (ie the name in archive), try tto use it like this :
for root, dirs, files in os.walk('A Folder'):
for f in files:
fname = os.path.join(root, f)
new_path = os.path.normpath(fname.replace('A Folder', ''))
myzip.write(fname, new_path)
精彩评论