mcluka mcluka - 1 year ago 94
Python Question

Saving a large matrix in to a .txt file in python

I would like to know what is the easiest way to save a large matrix, in my case with 640x640 elements, into a .txt file where it is easier to overview it.

I've been trying to convert every single element in to a string and then save it, but I never managed to get a correct, matrix-like organised .txt file.

So I would like to save the all the elements in the exact same order, maybe I would add an additional row and column to enumerate the rows (from -320 to +320) and columns.

I guess this is a common thing with some of you, that do this on a regular basis, so I would like to know, if anyone would be willing to share his knowledge and maybe show an example with a random matrix...


Answer Source

If you must put it in a text file, you could do something simple like this, which might be easier to follow than other answers:

def write_matrix_to_textfile(a_matrix, file_to_write):

    def compile_row_string(a_row):
        return str(a_row).strip(']').strip('[').replace(' ','')

    with open(file_to_write, 'w') as f:
        for row in a_matrix:

    return True

That should get you by. I didn't actually run this because I don't have a matrix to run it on. Let me know if it works out for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download