Converting elements of a list to a string and then iteratively listing each element in a text file

Consider this simple example

Suppose that we have the following list:

[[2, 3, 4], [5, 6, 7], [8, 9, 10]]

I would like to write each list in this list as a separate line in a text file. i.e...

2 3 4
5 6 7
8 9 10

To do that, I seems that you must convert each element to a string because object.write() expects a string (is there a better way to do this?). Now, for a single list like [2, 3, 4], I have been doing the following:

l = [2, 3, 4]
s = ' '.join(str(x) for x in l)
with open("file_open.txt", "+a") as file_object:
   file_object.write("\n")
   file_object.write(str(s))

How do I do this for a more complicated list like [[2, 3, 4], [5, 6, 7], [8, 9, 10]] where each element is iteratively listed in a text file as

2 3 4
5 6 7
8 9 10

Note: in the actual case that I am dealing with, it was originally a numpy array that I converted to a list, and it has the form

[[[1.5, 7.912834397348988, 148.46579073169295]], [[2.0, 7.912834397348988, 148.46579073169295]],...]]]

Like in the simple example that I gave, I need a text file in the form

1.5, 7.912834397348988, 148.46579073169295
2.0, 7.912834397348988, 148.46579073169295

It does not have to be a list. Would be be easier to keep it as a numpy array?

1 answer

  • answered 2021-07-27 15:58 Cory Kramer

    You could use numpy.savetxt to do this

    import numpy as np
    data = np.array([[2, 3, 4], [5, 6, 7], [8, 9, 10]])
    np.savetxt('file_open.txt', data)
    

    The default delimiter is ' ' and newline is '\n' but you can pass those arguments if you prefer something else.

    If you were to write this by hand, it would look something like

    data = [[2, 3, 4], [5, 6, 7], [8, 9, 10]]
    with open('file_open.txt') as f_out:
        for line in data:
            f_out.write(' '.join(str(i) for i in line) + '\n')
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum