Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested lists and saving into a text file

I have a nested list containing strings and integers that I'm trying to save into a txt file but I'm having trouble with formatting.

array = [(string1, int1),(string2, int2),(string3, int3),...(string_n, int_n)]
with open("output.txt", "w") as f:
    f.write(repr(array))

and get the array saved as is.

How do I format the output so that the format is as below instead of the array as is?

string1 int1
string2 int2
.
.
.
string_n int_n

This is propably a very newbie question, but I couldn't find anything similar with search...

like image 384
Aok_16 Avatar asked Dec 07 '25 19:12

Aok_16


1 Answers

Use the following:

array = [('s1', 1),('s2', 2)]

with open('out.txt', 'w') as f:
    for item in array:
        f.write('{} {}\n'.format(*item))

Output:

s1 1
s2 2
like image 151
ettanany Avatar answered Dec 09 '25 08:12

ettanany



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!