2

I have three lists in Python. I want to save these lists as a semicolon delimited text file (with a heading).

For example, lets consider these three lists:

l1 = ['a1', 'a2', 'a3', 'a4', 'a5']
l2 = [1,2,3,4,5]
l3 = [20.0, 25.1, 51.2, 60.2, 75.0]

and header, ['Label1', 'Label2', 'Label3']

I want these lists to be saved as columns in a text file in the following form:

Label1; Label2; Label3
a1;1;20.0%
a2;2;25.1%
a3;3;51.2%
a4;4;60.2%
a5;5;75.0%

In addition to saving the file in the above format, I want to have percentage symbols while writing the last column. I checked this post, but I am still confused about how I can implement this. I am using python 2.7.

I will really appreciate any help.

Ross
  • 109
  • 1
  • 7

3 Answers3

5

The following will work, using the csv module and zip:

l1 = ['a1', 'a2', 'a3', 'a4', 'a5']
l2 = [1,2,3,4,5]
l3 = [20.0, 25.1, 51.2, 60.2, 75.0]
header = ['Label1', 'Label2', 'Label3'] 

import csv

with open('output.csv', 'w') as f:
    w = csv.writer(f, delimiter=';')
    w.writerow(header)
    for row in zip(l1, l2, (str(x)+'%' for x in l3)):
        w.writerow(row)
user2390182
  • 72,016
  • 6
  • 67
  • 89
2
l1 = ['a1', 'a2', 'a3', 'a4', 'a5']
l2 = [1,2,3,4,5]
l3 = [20.0, 25.1, 51.2, 60.2, 75.0]
answer = ''
for i in range(len(l1)):
    value = "{0};{1};{2}%".format(l1[i], l2[i], l3[i])
    answer = answer+"\n"+value

header = ['Label1', 'Label2', 'Label3'] 
title = ';'.join(header)
answer = title + answer
print(answer)

file = open("answer.txt","w") 
file.write(answer)
file.close()
Alfred Ayi-bonte
  • 715
  • 7
  • 11
1

You can transpose your rows using zip and then process them with the csv module.

>>> import csv
>>> l1 = ['a1', 'a2', 'a3', 'a4', 'a5']
>>> l2 = [1,2,3,4,5]
>>> l3 = [20.0, 25.1, 51.2, 60.2, 75.0]
>>> l3_percent = ['{!r}%'.format(x) for x in l3]
>>> header = ['Label1', 'Label2', 'Label3']
>>> rows = zip(l1, l2, l3_percent)
>>>
>>> with open('out.csv', 'w') as f:
...:    writer = csv.writer(f, delimiter=';', quoting=csv.QUOTE_NONE)
...:    writer.writerow(header)
...:    writer.writerows(rows)

This produces

Label1;Label2;Label3
a1;1;20.0%
a2;2;25.1%
a3;3;51.2%
a4;4;60.2%
a5;5;75.0%

timgeb
  • 76,762
  • 20
  • 123
  • 145