Python – How to write a float list of lists to file in Python

file-iopython

I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple
file.write() and file.writelines()

do not work. Is there a conversion method I can employ that doesn't have me looping through all the lists (matrix = list of lists in my case) converting the individual values?

I guess I should clarify, that it needn't look like a matrix, just the associated values in an easy to parse list, as I will be reading in later. All on one line may actually make this easier!

Best Solution

m = [[1.1, 2.1, 3.1], [4.1, 5.1, 6.1], [7.1, 8.1, 9.1]]
file.write(str(m))

If you want more control over the format of each value:

def format(value):
    return "%.3f" % value

formatted = [[format(v) for v in r] for r in m]
file.write(str(formatted))