Aok_16
Aok_16

Reputation: 35

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...

Upvotes: 3

Views: 2846

Answers (4)

Omid
Omid

Reputation: 13

you can use numpy savetxt method:

import numpy as np 
np.savetxt("output.txt", array, fmt="%s", encoding="utf-8")

Upvotes: 0

Chinny84
Chinny84

Reputation: 966

You could use join instead

for sub_array in array:
     f.write(' '.join(sub_array) + '\n')

This will work for arbitrary length arrays.

If you have a list of lists rather than an array of mix types then you would need to coerce the elements to string before using the join (as pointed out by @Blckknght).

This could look like this

for sub_array in array:
     f.write(' '.join(map(str,sub_array)) + '\n')

Upvotes: 2

Patrick Haugh
Patrick Haugh

Reputation: 60944

for s, i in array:
    f.write('{} {}\n'.format(s, i))

The \n is needed since write does not include a newline.

Upvotes: 2

ettanany
ettanany

Reputation: 19806

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

Upvotes: 2

Related Questions