0

I have a directory of 170,000+ pickle files in multiple subdirectories which were originally pickled using the (protocol=0) format. This hasn't been very efficient time or space-wise.

I wrote a script to re-pickle (using cPickle, protocol=2) each file in the folder(s) but curiously, the script throws an exception while processing a particular file (file # 95,000). Initially, I thought that the pickle file is corrupted. When I try to load this exact pickle file from IPython command line, the file loads just fine.

So, I'm dumbfounded as to why this happens. Here's my script and I appreciate help:

import os
import cPickle
import numpy
import time
import re
from progressbar import ProgressBar

inpath = '/path/to/folder'



def list_files(dir):                                                                                                
    r = []                                                                                                           
    subdirs = [x[0] for x in os.walk(dir)]                                                                            
    for subdir in subdirs:                                                                                            
        files = os.walk(subdir).next()[2]                                                                             
        if (len(files) > 0):                                                                                          
            for file in files:                                                                                        
                r.append(subdir + "/" + file)                                                                        
    return r     



infileList = list_files(inpath)
print "Total number of files found: %d" % len(infileList)
print "\n\n"

progress = ProgressBar()

outfilename = " "

print "Processing pickle files. Pls wait..."
t0 = time.time()
filecount = 0

for file in progress(infileList):
    try:
        arr = cPickle.load(open(file , "rb" ))
        outfilename = re.sub('/initial/path/','/new/path/',file)

        if not os.path.exists(os.path.dirname(outfilename)):
            os.makedirs(os.path.dirname(outfilename))
        with open(outfilename, "wb") as f:
            cPickle.dump(arr,f,protocol=2)

        filecount = filecount + 1


    except Exception,e:

        print "\n" + str(filecount)
        print "\nError occured while processing file: " +  outfilename 
        tx = time.time()
        print "\n Time elapsed: %.2f" % (tx-t0)
        continue

t1 = time.time()

total = t1-t0

print "Files repickled with protocol=2.\nRepickling execution time: %.2f sec" % total

That1Guy
  • 7,075
  • 4
  • 47
  • 59
HuckleberryFinn
  • 1,489
  • 2
  • 16
  • 26

0 Answers0