Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python write varying-length list to txt file

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?

like image 962
Tom Avatar asked Aug 18 '26 22:08

Tom


2 Answers

Just use map and join:

a = [1,2,3]

with open('node.k','w') as file:
    file.write(','.join(map(str,a))+'\n')
like image 115
carrdelling Avatar answered Aug 20 '26 11:08

carrdelling


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'
like image 38
Christian Dean Avatar answered Aug 20 '26 11:08

Christian Dean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!