Logical python question - handeling directories and files in them

Posted by Konstantin on Stack Overflow See other posts from Stack Overflow or by Konstantin
Published on 2010-03-17T12:17:16Z Indexed on 2010/03/17 12:21 UTC
Read the original article Hit count: 247

Filed under:

Hello!

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.

© Stack Overflow or respective owner

Related posts about python