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!
The most Pythonic way to convert a list of strings to a list of floats is to use the list comprehension floats = [float(x) for x in strings] . It iterates over all elements in the list and converts each list element x to a float value using the float(x) built-in function.
What is a list of lists? In any programming language, lists are used to store more than one item in a single variable. In Python, we can create a list by surrounding all the elements with square brackets [] and each element separated by commas.
Method 2: write in a Text file In Python using writelines() The file is opened with the open() method in w mode within the with block, the argument will write text to an existing text file with the help of readlines().
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))
the following works for me:
with open(fname, 'w') as f:
f.writelines(','.join(str(j) for j in i) + '\n' for i in matrix)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With