Mostly Linux & Python syntax notes and hyperlinks.

Monday, May 15, 2017

python: Read in generic lookup table from tab-separated text file with field-names on top line

not beautiful yet, but here's a start:

lookup={}
fd=open("tab_separated_fields.txt", 'r')
try:
    headers=fd.readline()
    names=headers.split()
    num_fields=len(names)
    print "%d fields in %s" % (num_fields,names)

    for row, line in enumerate(fd,1) :
        print "row %d: line=%s" % (row,line)
        if len(line) > 10:
            values=line.split('\t')
            if len(values) == num_fields:
                lookup[str(row)] = {names[i]:(values[i]).strip() for i in range(num_fields)}
            else:
                print "row %d doesn't have %d values" % (row,num_fields)
finally:
    fd.close()
print lookup

Next, see if csv reader makes it better.
Actually, csv.DictReader.
e.g https://github.com/pargery/csv_utils2/blob/master/SimpleCSVReporter.py