Search code examples
pythondatabasecsvdatatablesheader

How to I add a header to a tsv in python?


persons = [
    {"name":"howard", "adress":"New Jersey", "blood group":"AB"},
    {"name":"harry", "adress":"New York", "blood group":"O"},

]

output_file = "outputfile.tsv"
with open(outfilename, "w") as output:    

    for row in persons:
        column_values = row.values()
        line = "\t".join(column_values) + '\n'
        output.write(line)

I tried using methods for csv but it didnt work furthermore I tried changing the dictionary but was not succesufull


Solution

  • Use csv module. In particular csv.DictWriter(). It can add the header using the dict keys as the field names and writeheader() to create the header. Then you write out the data using writerows().

    import csv
    
    persons = [
        {"name":"howard", "adress":"New Jersey", "blood group":"AB"},
        {"name":"harry", "adress":"New York", "blood group":"O"},
    
    ]
    
    output_file = "outputfile.tsv"
    
    with open(output_file, 'w') as csv_file:
        hdr = persons[0].keys()
        csvDictR = csv.DictWriter(csv_file, hdr, delimiter='\t')
        csvDictR.writeheader()
        csvDictR.writerows(persons)
    
    cat outputfile.tsv
    name    adress  blood group
    howard  New Jersey      AB
    harry   New York        O