Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Load the contents of the provided file path and generate a set of
- # class instances of the specified type; return a list of created instances.
- # All extra parameters are passed to the constructor of the class alongside
- # the loaded record.
- def loadRecords(filePath, classType, *args, **kwargs):
- filehandle = open(filePath, 'r')
- try:
- records = json.load(filehandle)
- except Exception, e:
- print "Data file %s is not valid JSON: %s" % (filePath, e)
- raise e
- filehandle.close()
- result = []
- for i, record in enumerate(records):
- try:
- result.append(classType(record, *args, **kwargs))
- except Exception, e:
- # Figure out roughly where in the file we were when we failed.
- # Tricky, since we loaded the entire file correctly, but one of
- # the records in it was faulty in a JSON-compatible way.
- # For now, assuming that any line that begins with a '{' is a
- # new record.
- filehandle = open(filePath, 'r')
- lineNum = 0
- curIndex = 0
- didFindRecord = False
- for j, line in enumerate(filehandle):
- lineNum += 1
- if line[0] == '{':
- curIndex += 1
- if curIndex == i:
- print "Failed to load record %d starting on line %d from data file %s:" % (i, lineNum, filePath)
- didFindRecord = True
- break
- if not didFindRecord:
- print "Failed to load record %d from data file %s:" % (i, filePath)
- traceback.print_exc()
- sys.exit()
- return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement