import platform #Globals currOS = platform.platform() if currOS.find('Windows') == 0: LOCALBASE = 'D:/website/' #LOCALBASE = 'A:/test/' else: LOCALBASE = '/mnt/d/website/' TYPEFILE = LOCALBASE + "types.tsv" HIERFILE = LOCALBASE + "types.json" ERRFILE = LOCALBASE + "hiererr.txt" flErr = open(ERRFILE, "w", encoding='latin1') def get_type_list(flTypes): typeList = [] stType = flTypes.read() lsIn = stType.split('\n') n = 0 for line in lsIn: n += 1 #get rid of leading tabs line = line.strip() # ignore blank lines if line == "": continue # or commented out lines if line[0] == "#": continue lsRec = line.split('\t') # all lines should have exactly one type and its parent if len(lsRec) > 2: stErr = "Length of line " + str(n) + "> 2: " + line + "\n" flErr.write(stErr) continue for liType in typeList: if lsRec[0] == liType[0]: stErr=lsRec[0] + " on line " + str(n) + " is a duplicate.\n" flErr.write(stErr) continue typeList.append(lsRec) return typeList def write_hierarchy(flHier, typeList): stOut = '[\n' for entry in typeList: if len(entry) == 1: # last entry will be "type": "unknown". So skip the comma. if entry[0] == "unknown": stEntry='\t{\n\t' + '"type": "' + entry[0] +\ '",\n\t"parent":null' + '\n\t}' else: stEntry='\t{\n\t' + '"type": "' + entry[0] +\ '",\n\t"parent":null' + '\n\t},\n' else: stEntry='\t{\n\t' + '"type": "' + entry[0] +\ '",\n\t"parent": "' + entry[1] + '"\n\t},\n' stOut += stEntry stOut += '\n]' flHier.write(stOut) # end write_hierarchy def main(): flTypes = open(TYPEFILE, "r", encoding='latin1') if not flTypes: stErr = "Cannot read ", TYPEFILE flErr.write(stErr) return False flHier = open(HIERFILE, "w", encoding='latin1') if not flHier: stErr = "Cannot write to ", HIERFILE flErr.write(stErr) return False typeList = get_type_list(flTypes) write_hierarchy(flHier, typeList) # end main if __name__ == "__main__": main()