Question

Using the zipfile module I have created a script to extract my archived files, but the method is corrupting everything other than txt files.

def unzip(zip):
         filelist = []
         dumpfold = r'M:\SVN_EReportingZones\eReportingZones\data\input\26012012'
         storage = r'M:\SVN_EReportingZones\eReportingZones\data\input\26012012__download_dump'
         file = storage + '\\' + zip
         unpack = dumpfold + '\\' + str(zip)
         print file

         try:

                     time.sleep(1)
                     country = str(zip[:2])
                     countrydir =  dumpfold + '\\' + country
                     folderthere = 0
                     if exists(countrydir):
                        folderthere = 1           

                     if folderthere == 0:
                       os.makedirs(countrydir)

                     zfile = zipfile.ZipFile(file, 'r')
##                     print zf.namelist()
                     time.sleep(1)
                     shapepresent = 0

Here I have a problem - by reading and writing the zipped data, the zipfile command seems to be rendering it unusable by the programs in question - I am trying to unzip shapefiles for use in ArcGIS...

                     for info in zfile.infolist():
                         fname = info.filename
                         data = zfile.read(fname)
                         zfilename = countrydir + '\\' + fname
                         fout = open(zfilename, 'w')# reads and copies the data
                         fout.write(data)
                         fout.close()
                         print 'New file created ----> %s' % zfilename





         except:
                        traceback.print_exc()
                        time.sleep(5)

Would it be possible to call WinRar using a system command and get it to do my unpacking for me? Cheers, Alex

EDIT

Having used the wb method, it works for most of my files but some are still being corrupted. When I used winRar to manually unzip the problematic files they load properly, and they also show a larger ile size.

Please could somebody point me in the direction of loading winRar for the complete unzip process?

Was it helpful?

Solution

You are opening the file in a text mode. Try:

       fout = open(zfilename, 'wb')# reads and copies the data

The b opens the file in a binary mode, where the runtime libraries don't try to do any newline conversion.

OTHER TIPS

To answer the second section of your question, I suggest the envoy library. To use winRar with envoy:

import envoy
r = envoy.run('unrar e {0}'.format(zfilename))
if r.status_code > 0:
    print r.std_err
print r.std_out

To do it without envoy:

import subprocess
r = subprocess.call('unrar e {0}'.format(zfilename), shell=True)
print "Return code for {0}: {1}".format(zfilename, r)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top