Using Spyder / Python to Open. Npy File

Using Spyder / Python to Open. Npy File

Sorry. I'm just now learning Python and everything there is to do with data analysis.

How on earth do I open a .npy file with Spyder? Or do I have to use another program? I'm using a Mac, if that is at all relevant.

3

5 Answers

*.npy files are binary files to store numpy arrays. They are created with

import numpy as np

data = np.random.normal(0, 1, 100)
np.save('data.npy', data)

And read in like

import numpy as np
data = np.load('data.npy')
3

Given that you asked for Spyder, you need to do two things to import those files:

  1. Select the pane called Variable Explorer
  2. Press the import button (shown below), select your .npy file and present Ok.

Then you can work with that file in your current Python or IPython console.

1

.npy files are binary files. Do not try to open it with Spyder or any text editor; what you see may not make sense to you.

Instead, load the .npy file using the numpy module (reference: ).

Code sample:

First, import numpy. If you do not have it, install (here's how: )

>>> import numpy as np

Let's set a random numpy array as variable array.

>>> array = np.random.randint(1,5,10)
>>> print array
[2 3 1 2 2 3 1 2 3 3]

To export to .npy file, use np.save(FILENAME, OBJECT) where OBJECT = array

>>> np.save('test.npy', array)

You can load the .npy file using np.load(FILENAME)

>>> array_loaded = np.load('test.npy')

Let's compare the original array vs the one loaded from file (array_loaded)

>>> print 'Loaded:  ', array_loaded
Loaded:   [2 3 1 2 2 3 1 2 3 3]

>>> print 'Original:', array
Original: [2 3 1 2 2 3 1 2 3 3]
2
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
import glob


for filename in glob.glob("*.*"):
    if '.npy' in filename:
        img_array = np.load(filename, allow_pickle=True)
        plt.imshow(img_array, cmap="gray")
        img_name = filename+".png"
        matplotlib.image.imsave(img_name, img_array)
        print(filename)

creates a png file for each image in the current directory that is of the format .npy. For example, I have this RGB image and its depth image is in .npy format. Converting it to png gives me so:

Just use the full path of the .npy file. For example,

import numpy as np
data = np.load('/home/user/npyfolder/npyfile.npy')
print(data)
# Or Either save it to the text file or something.

I was also having the path issue, but When I changed the path from relative to an absolute path, It worked.!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.