Computer_Engineer
Computer_Engineer

Reputation: 403

Extract files that exist in folders from Zip Archive

How can i extract files from directory that exist in Zip Archive,i uploaded zip archive from form(written in HTML),now if the Zip Archive contains folders i can't extract the files in side this folder,this is a snippet from my code:

form = cgi.FieldStorage() 
file_upload = form['file']
zfile=zipfile.ZipFile(file_upload.file,"r")
files_zip=zfile.namelist()
for name in files_zip:
  print name
  if name.endswith('/'):
      print "yes"
      l=list()
      l=os.listdir(name)
      print l

EDIT: I tried to use StringIO() as:

s=StringIO(file_upload)
f=s.getvalue()
with zipfile.ZipFile(f,'r')as z:
         for d in z.namelist():
               print "%s: %s"%(d, z.read(d))

but the problem of the second snippet of code is:

No such file or directory: "FieldStorage('file', 'test.zip')

,i want to extract thse files to add them to GAE BlobStore??

Thanks in advance.

Upvotes: 0

Views: 1260

Answers (2)

Anurag Uniyal
Anurag Uniyal

Reputation: 88865

I don't understand why you are using os.listdir to list files inside zip data, you should just go thru names and extract data, here is a example where I create a in-memory zip file and extract files, even in a folder e.g.

from zipfile import ZipFile
from StringIO import StringIO

# first lets create a zip file with folders to simulate data coming from user
f = StringIO()
with ZipFile(f, 'w') as z:
    z.writestr('1.txt', "data of file 1")
    z.writestr('folder1/2.txt', "data of file 2")

zipdata = f.getvalue()

# try to read zipped data containing folders
f = StringIO(zipdata)
with ZipFile(f, 'r') as z:
    for name in z.namelist():
        print "%s: %s"%(name, z.read(name))

output:

1.txt: data of file 1
folder1/2.txt: data of file 2

As appengine doesn't allow writing to file system you will need to read file data (explained aboce) and dump it to blobs, you can just have a simple structure of name and data, but in you local OS you can try z.extractall() and it will create whole folder structure and files.

Upvotes: 2

Dave W. Smith
Dave W. Smith

Reputation: 24966

There's a working example of how to do this in appengine-mapreduce.

Look at input_readers.py for BlobstoreZipInputReader (which starts at line 898 at the moment).

Upvotes: 3

Related Questions