tags:

views:

1110

answers:

4

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, but thanks to all for your thouhts!

+4  A: 

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)
SilentGhost
+3  A: 
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))
John Millikin
str(m) produces something different
SilentGhost
different from what?
John Millikin
Oh, you wrote the other solution. Yes, depending on how the output should be formatted (comma-separated, etc), manual string building might be required.
John Millikin
I don't think that representation of a matrix is what OP asks for.
SilentGhost
Actually, I like seeing (and upvoted) both your solutions. I admit I also first interpreted the question the way SilentGhost did, but after reading John's solution I have to say that the question leaves the exact output format to inference.
Jarret Hardie
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, but thanks to all for your thouhts!
Fry
+5  A: 

Why not use pickle?

import cPickle as pickle
pckl_file = file("test.pckl", "w")
pickle.dump([1,2,3], pckl_file)
pckl_file.close()
nikow
A: 
import pickle

# write object to file
a = ['hello', 'world']
pickle.dump(a, open('delme.txt', 'wb'))

# read object from file
b = pickle.load(open('delme.txt', 'rb'))
print b        # ['hello', 'world']

At this point you can look at the file 'delme.txt' with vi

vi delme.txt
  1 (lp0
  2 S'hello'
  3 p1
  4 aS'world'
  5 p2
  6 a.
russian_spy