TTT
TTT

Reputation: 4434

Python write a list to a text file

I am using python format method to write a list of numbers into a text file. When the list length is fixed I can do:

a = [16,1,16,1]
myfile.write('{0},{1},{2},{3}'.format(*a) + "\n")

My question is how to use the format method when the size of list is not fixed. Is there any easy easy way of doing this? Rather than first create a string b, and then map a to b. I am not sure if I can use something like myfile.write('{all elements in a}'.format(*a) + "\n")

b=''
for i in range(len(a)):
    if i<(len(a)-1):
        b=b+'{'+ str(i) + '},'
    else:
        b=b+'{'+ str(i) + '}'

myfile.write(b.format(*a) + "\n")

Upvotes: 0

Views: 262

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

Use str.join:

>>> lis = [16,1,16,1]
>>> ','.join(str(x) for x in lis) + '\n'
'16,1,16,1\n'
>>> lis = range(10)
>>> ','.join(str(x) for x in lis) + '\n'
'0,1,2,3,4,5,6,7,8,9\n'

Upvotes: 2

Related Questions