11

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!

1
  • Can you explain? Why does file.write() not work for you? Commented May 14, 2009 at 18:23

5 Answers 5

16
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))
Sign up to request clarification or add additional context in comments.

6 Comments

str(m) produces something different
Oh, you wrote the other solution. Yes, depending on how the output should be formatted (comma-separated, etc), manual string building might be required.
I don't think that representation of a matrix is what OP asks for.
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.
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!
|
11

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)

Comments

5

Why not use pickle?

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

1 Comment

2

for row in matrix: file.write(" ".join(map(str,row))+"\n")

This works for me... and writes the output in matrix format

Comments

1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.