I want to output a list into a txt file with format. But the list length will change from time to time.
The code is like this:
a = [1, 2, 3] #**but this could also be: a = [1, 2, 3, 6, 9] or [1, 90]**
with open('node.k','w') as file:
file.write(((len(a)-1)*'{},'+'{}\n').format(a[0],a[1],a[2]))
I was wondering how should I modify this code so that this code can work for different list length?
Just use map and join:
a = [1,2,3]
with open('node.k','w') as file:
file.write(','.join(map(str,a))+'\n')
As said in the comment, you can do this by unpacking your list into str.format():
>>> a = [1, 2, 3]
>>> ((len(a)-1)*'{},'+'{}\n').format(*a)
'1,2,3\n'
>>> a = [1, 2, 3, 7, 60]
>>> ((len(a)-1)*'{},'+'{}\n').format(*a)
'1,2,3,7,60\n'
By doing this, you avoid having to explicitly pass in a by each of its indexes. But this can be done cleaner using map() and str.join():
>>> a = [1, 2, 3]
>>> ','.join(map(str, a)) + '\n'
'1,2,3\n'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With