Logical python question - handling directories and files in them
I'm using this function to extract files from .zip archive and store it on the server:
def unzip_file_into_dir(file, dir):
import sys, zipfile, os, os.path
os.makedirs(dir, 0777)
zfobj = zipfile.ZipFile(file)
for name in zfobj.namelist():
if name.endswith('/'):
os.mkdir(os.path.join(dir, name))
else:
outfile = open(os.path.join(dir, name), 'wb')
outfile.write(zfobj.read(name))
outfile.close()
And the usage:
unzip开发者_开发技巧_file_into_dir('/var/zips/somearchive.zip', '/var/www/extracted_zip')
somearchive.zip have this structure:
somearchive.zip
1.jpeg
2.jpeg
another.jpeg
or, somethimes, this one:
somearchive.zip
somedir/
1.jpeg
2.jpeg
another.jpeg
Question is: how do I modify my function, so that my extracted_zip
catalog would always contain just images, not images in another subdirectory, even if images are stored in somedir
inside an archive.
Use
outfile = open(os.path.join(dir, os.path.basename(name)), 'wb')
to strip the path from the name of the ZIP entry. This way, only the filename is left and you don't get any directories. You must also comment out the os.mkdir()
or replace it with pass
.
精彩评论