3

I have a zip file that has a path. When I unzip the file using python and put it in my target folder, it then creates all of the files in the path inside my target folder.

Target: d:\unzip_files zip file has a path and file name of: \NIS\TEST\Files\tnt.png

What happens: d:\unzip_files\NIS\TEST\Files\tnt.png

Is there a way to hae it just unzip the tnt.png file into d:\unzip_files? Or will I have to read down the list and move the file and then delete all of the empty folders?

import os, sys, zipfile

zippath = r"D:\zip_files\test.zip"
zipdir = r"D:\unzip_files"

zfile = zipfile.ZipFile(zippath, "r")
for name in zfile.namelist():
    zfile.extract(name, zipdir)
zfile.close()

So, this is what worked..

import os, sys, zipfile

zippath = r"D:\zip_files\test.zip"
zipdir = r"D:\unzip_files"

zfile = zipfile.ZipFile(zippath, "r")
for name in zfile.namelist():
    fname = os.path.join(zipdir, os.path.basename(name))
    fout = open(fname, "wb")
    fout.write(zfile.read(name))

fout.close()

Thanks for the help.

user1015375
  • 63
  • 1
  • 6

1 Answers1

1

How about reading file as binary and dump it? Need to deal cases where there is pre-existing file.

for name in zfile.namelist():

    fname = os.path.join(zipdir, os.path.basename(name))
    fout = open(fname, 'wb')
    fout.write(zfile.read(name))
yosukesabai
  • 6,184
  • 4
  • 30
  • 42
  • OK worked great kind of. With one item in the zip it didn't work(name but no data) with 2 items it did the first one fine, but the second has a file name, but nothing in it. So it reads the last one and creats the name but doesn't put the data in it. Then realized I had forgotten to change my .close to "fout.close(). I put the fixed code in the origional post. – user1015375 Oct 27 '11 at 14:36
  • didn't realize .close() was necessary. Glad to know that it worked for ya. – yosukesabai Oct 27 '11 at 19:06