CharlieShe
CharlieShe

Reputation: 63

Writing two lists with different length as columns to a data file

I am considering the two list: a = [2, 4, 7] b = [6, 9, 10, 90, 80]

I want to write these lists to a data file to show the elements of list 'a' in one column and of 'b' in the second column taking into consideration that a and b are not the same length.

Upvotes: 1

Views: 2213

Answers (2)

eumiro
eumiro

Reputation: 212885

import itertools as it
import csv

with open('output.csv', 'w') as f:
    csvw = csv.writer(f)
    for aa, bb in it.izip_longest(a, b):
        csvw.writerow(aa, bb)

or a shorter version inspired by @katriealex:

with open('output.csv', 'w') as f:
    csv.writer(f).writerows(it.izip_longest(a, b))

Upvotes: 6

Abhijit
Abhijit

Reputation: 63737

A small variation from @eumiro

with open("test.txt","w") as fin:
    #izip_longest create consecutive tuples of elements from the list of iterables
    #where if any of the iterable's length is less than the longest length of the
    #iterable, fillvalue is taken as default
    #If you need formatted output, you can use str.format
    #The format specifier here used specifies the length of each column
    #to be five and '^' indicates that the values would be center alligned
    for e in izip_longest(a,b,fillvalue=''):
         print >>fin,"{:^5} {:^5}".format(*e)
         #if you are using Python 3.x
         #fin.write("{:^5} {:^5}\n".format(*e))

Upvotes: 1

Related Questions