Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

write to csv file two lists separated by tab error

I have to lists

a = [1,2,3,4]
b = [[2,3,4,5],[2,4,3,9], [9,4,6,8], [7,3,8,5]]

I have written it to a csv file with delimiter as tab. Now I don’t want to have the nested list as [2,3,4,5] but only the element 2,3,4,5. I don’t know how to get rid of the the list brackets.

Here is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

with open('output.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
wr = csv.writer(myfile, delimiter='\t')
wr.writerows(zip(a,b))

output of my code:

1   [2, 3, 4, 5]
2   [2, 4, 3, 9]
3   [9, 4, 6, 8]
4   [7, 3, 8, 5]

But I want to have

1   2, 3, 4, 5
2   2, 4, 3, 9
3   9, 4, 6, 8
4   7, 3, 8, 5

Thanks!

>Solution :

The second column is the default str() of a list. You can format the second column as a custom string to get what you want:

import csv

a = [1,2,3,4]
b = [[2,3,4,5],[2,4,3,9], [9,4,6,8], [7,3,8,5]]

with open('output.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
    wr = csv.writer(myfile, delimiter='\t')
    for col1,col2 in zip(a, b):
        str_col2 = ', '.join([str(n) for n in col2])
        wr.writerow([col1, str_col2])

Output:

1       2, 3, 4, 5
2       2, 4, 3, 9
3       9, 4, 6, 8
4       7, 3, 8, 5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading