1

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.

2 Answers 2

2
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])
Sign up to request clarification or add additional context in comments.

1 Comment

Little typo - tsv.writerow(output_columns) should be tsv_output.writerow(output_columns). Otherwise good
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.