Home > Software design >  How to I add a header to a tsv in python?
How to I add a header to a tsv in python?

Time:12-28

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

CodePudding user response:

To add a header to the TSV file, you can simply write the header line to the file before writing the data rows.

Here is an example of how you can do this:

output_file = "outputfile.tsv"

# Create a list of column names
column_names = ["name", "adress", "blood group"]

with open(output_file, "w") as output:
    # Write the header line
    header = "\t".join(column_names)   '\n'
    output.write(header)

    # Write the data rows
    for row in persons:
        column_values = row.values()
        line = "\t".join(column_

CodePudding user response:

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
  • Related