mardi 4 août 2015

Python How to copy files inside a zip to another zip in memory?

Purpose

Split a zip archive into smaller zip archives with an evenly distributed # of files per new zip.

Example

source zip (100 files)

  • src/100-Test.zip

destination zips (25 files each):

  • destination/1.zip
  • destination/2.zip
  • destination/3.zip
  • destination/4.zip

Description

So I have been able to open the zip file and iterate through the contents to split them up, but I have not been able to write to the file. Since I didn't do anything with the zip contents I didn't think I had to do any StringIO stuff or anything?

Code

zipFileNameSrc = '100-Test.zip'
zipFile = open(zipFileNameSrc)
unzippedFile = zipfile.ZipFile(zipFile)
imgList = [(s, unzippedFile.read(s)) for s in unzippedFile.namelist() if (".jpg" or ".JPG") in s]
#image names: imgList[i][0]  and  images: imgList[i][1]

#...
#...additional logic to split into sets of 25 images
#...fileTuplesList = imgList[:25]
zipNo = 1
#zipFileDest = destination + "/" + zipSrcNm + "/" + zipNo.__str__() + ".zip"
zipFileName = zipNo.__str__() + ".zip"
zipOut = zipfile.ZipFile(zipFileName, 'w')
for i in xrange(len(fileTuplesList)):
    fileNameAndPath = fileTuplesList[i][0]
    actualFile = fileTuplesList[i][1]
    zipOut.write(fileNameAndPath, actualFile)
zipOut.close()
#move_files(zipFileName, zipFileDest)

Error

I get on this on line zipOut.write(fileNameAndPath, actualFile)

OSError: [Errno 2] No such file or directory: '100-Test/17.jpg'

Bonus

How to save the zip file to a different folder than where my script is?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire