Advertisement
Guest User

Untitled

a guest
Dec 4th, 2012
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. ## Load the contents of the provided file path and generate a set of
  2. # class instances of the specified type; return a list of created instances.
  3. # All extra parameters are passed to the constructor of the class alongside
  4. # the loaded record.
  5. def loadRecords(filePath, classType, *args, **kwargs):
  6.     filehandle = open(filePath, 'r')
  7.     try:
  8.         records = json.load(filehandle)
  9.     except Exception, e:
  10.         print "Data file %s is not valid JSON: %s" % (filePath, e)
  11.         raise e
  12.     filehandle.close()
  13.     result = []
  14.     for i, record in enumerate(records):
  15.         try:
  16.             result.append(classType(record, *args, **kwargs))
  17.         except Exception, e:
  18.             # Figure out roughly where in the file we were when we failed.
  19.             # Tricky, since we loaded the entire file correctly, but one of
  20.             # the records in it was faulty in a JSON-compatible way.
  21.             # For now, assuming that any line that begins with a '{' is a
  22.             # new record.
  23.             filehandle = open(filePath, 'r')
  24.             lineNum = 0
  25.             curIndex = 0
  26.             didFindRecord = False
  27.             for j, line in enumerate(filehandle):
  28.                 lineNum += 1
  29.                 if line[0] == '{':
  30.                     curIndex += 1
  31.                     if curIndex == i:
  32.                         print "Failed to load record %d starting on line %d from data file %s:" % (i, lineNum, filePath)
  33.                         didFindRecord = True
  34.                         break
  35.             if not didFindRecord:
  36.                 print "Failed to load record %d from data file %s:" % (i, filePath)
  37.             traceback.print_exc()
  38.             sys.exit()
  39.     return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement