nad
nad

Reputation: 2850

Writing to a tsv file from multiple list in Python

I have two lists

ids = [1,2,3]
values = [10,20,30]

I need to create a tsv file with two columns - id and result and put the ids and values in there. The output should look like this

id result
1  10
2  20
3  30

I wrote below code

output_columns = ['id','result']
data = zip(output_columns, ids, values)
    with open('output.tsv', 'w', newline='') as f_output:
        tsv_output = csv.writer(f_output, delimiter='\t')
        tsv_output.writerow(data)

But this gives me an output like below which is wrong

('id', '1', '10') ('result', '2','20')

I understand that this wrong output is because the way I did zip to create a row of data. But I am not sure how to solve it.

Please suggest.

Upvotes: 1

Views: 1567

Answers (2)

Onyambu
Onyambu

Reputation: 79208

output_columns = ['id','result']
data = zip(ids, values)
    with open('output.tsv', 'w', newline='') as f_output:
        tsv_output = csv.writer(f_output, delimiter='\t')
        tsv_output.writerow(output_columns)
        for id, val in data:
            tsv_output.writerow([id, val])

Upvotes: 2

bigbounty
bigbounty

Reputation: 17368

It's easier using pandas

In [8]: df = pd.DataFrame({"ids":[1,2,3], "values":[10,20,30]})

In [9]: df
Out[9]:
   ids  values
0    1      10
1    2      20
2    3      30

In [10]: df.to_csv("data.tsv", sep="\t", index=False)

Upvotes: 2

Related Questions