user1631306
user1631306

Reputation: 4470

write multiple list in file as columns

I have three lists

list1 = ['123','124','125']
list2 = [0.223333, 0.3434344, 0.4545454]
list3 = [ 0.53434, 0.453535, 0.534343]

list1 is list of str; list2 and list3 are float64. I want to print them in a file like

123 0.223333 0.53434
124 0.343434 0.453535
125 0.454545 0.534343

I tried

writer = csv.writer(writeCSVfile, delimiter=',', lineterminator='\n', quotechar='"')
row_list = zip(list1, str(list2), str(list3))
for row in row_list: 
    writer.writerows(row)

But I getting digits printed out in weird manner.

Upvotes: 1

Views: 68

Answers (2)

Athena
Athena

Reputation: 3228

Don't make a string out of the other two lists. That turns them into an iterator over the characters in the string rather than the elements in the list.

Try this instead: row_list = zip(list1, list2, list3)

Oh, and if you're only writing one row, use writerow instead of writerows

Upvotes: 4

JLuxton
JLuxton

Reputation: 461

Pandas is well suited for this.

import pandas as pd

list1 = ['123','124','125']
list2 = [0.223333, 0.3434344, 0.4545454]
list3 = [ 0.53434, 0.453535, 0.534343]

df = pd.DataFrame({'l1': list1, 'l2': list2, 'l3': list3})
df.to_csv('filename.csv')

Upvotes: 2

Related Questions