Python Forum
save 2d array to file and load back
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
save 2d array to file and load back
#1
I tried to save 2 dimensional array to a file and load it back. But not sure how to fix it. please advise. thanks.
import numpy as np
x = [['ABC', 123.45], ['DEF', 678.90]]
np.savetxt('text.txt',x)
y = np.loadtxt('text.txt')
Reply
#2
Default format string (fmt parameter) for the np.savetxt method coincide to floating point numbers, so, you need to change fmt to '%s' (strings):

import numpy as np
x = [['ABC', 123.45], ['DEF', 678.90]]
np.savetxt('text.txt', x, fmt='%s')

# default dtype for  np.loadtxt is also floating point, change it, to be able to load mixed data.
y = np.loadtxt('text.txt', dtype=np.object) 
Reply
#3
Is it a way to keep y same type (list) as x after loaded? Thanks.
Reply
#4
You can convert y to list using .tolist() method, e.g.

y = np.loadtxt('text.txt', dtype=np.object)
y = y.tolist()
Another way is to use standard pickle module.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [solved] Save a matplotlib figure into hdf5 file paul18fr 1 2,470 Jun-08-2021, 05:58 PM
Last Post: paul18fr
  Fatal Python error: initfsencoding: unable to load the file system codec gauravbhardwajee 12 28,033 Apr-30-2020, 07:45 PM
Last Post: barrpath
  Read file Into array with just $0d as Newline lastyle 5 3,309 Feb-03-2020, 11:58 PM
Last Post: lastyle
  Send array of doubles to Python from C and back baptiste 8 8,615 Jan-10-2020, 05:02 PM
Last Post: cencen_cj
  Corrupted numpy arrays when save to file. DreamingInsanity 2 3,183 Dec-14-2019, 12:12 PM
Last Post: DreamingInsanity
  save my sensor data from the bme680 into a json or csv file Plastefuchs84 1 3,103 Aug-23-2019, 03:04 AM
Last Post: Plastefuchs84
  Is there a way to save a CSV file as a python object amjass12 4 2,679 Jul-16-2019, 12:00 PM
Last Post: amjass12
  Is there any way to properly load fixed width file into a dataframe using Pandas? vicky53 1 3,031 Mar-29-2019, 06:04 PM
Last Post: Larz60+
  Load .abf file and for analysis with Pandas finalcode 0 2,982 Nov-10-2018, 09:51 AM
Last Post: finalcode
  loading a 3D array from a bin file Mark3232 1 4,663 May-04-2018, 11:36 AM
Last Post: j.crater

Forum Jump:

User Panel Messages

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