1

On the code bellow I want to save an array to a file in a single line using "numpy.savetxt" but I'm really not sure if I can get this result.

import numpy as np

if __name__ == '__main__':
    array = np.array([[ 6, -2.86751284, -0.35808319,  1.79360812],
        [ 6., -1.59351284, -0.02808319, -0.47039188],
        [ 6., 0.51848716,  0.21791681,  0.17060812],
        [ 6., 1.63251284, -0.12208319,  0.90460812],
        [ 6., -0.26051284,  0.03991681,  1.33660812],
        [ 6., 1.87948716,  0.43391681,  0.21960812],
        [ 6., 2.52048716,  0.45191681,  1.44760812],
        [ 6., 0.40448716,  0.04591681,  2.58360812],
        [ 6., 1.81248716,  0.30391681,  2.62260812]], np.float32)

    np.savetxt("img/file.txt", array, fmt="%.3d")

I wanted a result like "006, -002, -003, 001, 006, -001..." with all columns and lines in a single line in the file but separated by commas. Can I do it with "numpy.savetxt" or do I have to loop through array to get this result?

Thank you.

3
  • What do you get in the file if you try running it? Commented Sep 25, 2017 at 2:16
  • Did You try it? What happened? please take the time to read How to Ask. Commented Sep 25, 2017 at 2:19
  • When I ran this code I get a file with 9 lines and 3 columns. Commented Sep 25, 2017 at 19:44

1 Answer 1

6

This should produce, what you want:

np.savetxt("file.txt", array.flatten(), fmt="%.3d", newline = ", ")

cat file.txt
006, -002, 000, 001, 006, -001, 000, 000, 006, 000, 000, 000, 006, 001, 
000, 000, 006, 000, 000, 001, 006, 001, 000, 000, 006, 002, 000, 001, 
006, 000, 000, 002, 006, 001, 000, 002,
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.