开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜