Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a float list of lists to file in Python

Tags:

python

file-io

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!

like image 721
Fry Avatar asked May 14 '09 18:05

Fry


People also ask

How do I make a list float in Python?

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.

How do you make a list of lists in Python?

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.

How do I make a list in a text file?

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


2 Answers

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))
like image 153
John Millikin Avatar answered Sep 30 '22 22:09

John Millikin


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)
like image 28
SilentGhost Avatar answered Sep 30 '22 21:09

SilentGhost