Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
numpy.savetxt()
#1
Hi,

this code works fine:

import numpy as np
  
data = np.array([3,2,55,4])

for i in range(4):
    data[i] = data[i]+3

    print("text before", data[i], "text after")
Output:
Output:
~/pro$ python max.py ('text before', 6, 'text after') ('text before', 5, 'text after') ('text before', 58, 'text after') ('text before', 7, 'text after')
But I can't save in the file output.txt.
I tried with numpy.savetxt()

np.savetxt("output.txt", ???, fmt='%i', delimiter=",")
What should i add in this code?

Thanks

m.
Reply
#2
Can do it like this,since you take values out of the numpy arrary.
import numpy as np

data = np.array([3,2,55,4])
with open('output.txt', 'w') as f_out:
    for i in range(4):
        data[i] = data[i]+3
        print(f"text before, {data[i]}, text after")
        f_out.write(f"text before, {data[i]}, text after\n")
Output:
text before, 6, text after text before, 5, text after text before, 58, text after text before, 7, text after
Reply
#3
(Jun-26-2021, 07:16 AM)snippsat Wrote: Can do it like this,since you take values out of the numpy arrary.
import numpy as np

data = np.array([3,2,55,4])
with open('output.txt', 'w') as f_out:
    for i in range(4):
        data[i] = data[i]+3
        print(f"text before, {data[i]}, text after")
        f_out.write(f"text before, {data[i]}, text after\n")
Output:
text before, 6, text after text before, 5, text after text before, 58, text after text before, 7, text after

Now it works fine.

Thank you,

m.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Numpy savetxt, how save number with decimal separator SpongeB0B 1 3,351 May-10-2020, 01:05 PM
Last Post: ThomasL

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020