-1

I have a multidimensional numpy array arr1which I would like to save to a binary file in the .npy format.

import numpy as np
import os

current_dir_path = "/Users/.../desktop"

os.chdir(current_dir_path)    # changed to "desktop" subdirectory

filename = "my_array.npy"     # create name for numpy array file

np.save(filename, arr1)       # save the numpy array arr1 with filename my_array.npy

I have multiple subdirectories where I would like to save this file, e.g. "public", "desktop", "downloads", etc.

Question 1: How do I save this file into multiple subdirectories with this script? I don't think using os.chdir() makes sense.

Question 2: How do I do this such that if there is one "error" (e.g. I set up the path incorrectly for one subdirectory, it continues rather than throwing an error and not working with the other subdirectories?)

ShanZhengYang
  • 16,511
  • 49
  • 132
  • 234
  • Sounds like a great use case for HDF5, e.g. via [PyTables](http://www.pytables.org/) or [hd5py](http://www.h5py.org/). It gives you native support for NumPy's formats, and a hierarchical data structure. – Matt Hall Feb 11 '16 at 13:26
  • @kwinkunks That's a good recommendation, but it's overkill for what I need at the moment. Thank you though – ShanZhengYang Feb 11 '16 at 15:05

2 Answers2

0

Something like this should work (sorry I've not tested it):

base_path = "/Users/.../"
directories = ['desktop','public','downloads']

for directory in directories:
    filename = os.path.join(base_path,directory,"my_array.npy")
    np.save(filename, arr1)

and to answer your second question, enclosing in 'try..except'

for directory in directories:
    try:
        filename = os.path.join(base_path,directory,"my_array.npy")
        np.save(filename, arr1)
    except:
        print('Error writing to: {0} directory'.format(directory))
Colin Dickie
  • 910
  • 4
  • 9
0
  1. The pathname can be prepended to the filename in the call to np.save making the call to os.chdir unnecessary:

    np.save(current_dir_path +'/'+filename, arr1)

    np.save(second_dir_path+'/'+filename,arr1)

  2. Each save can be inside a try-except such that a raised error is caught:

    try: np.save(...) except Exception as e: print('Trouble saving array'+str(e))

If this save fails the message prints and execution continues

Keith Brodie
  • 657
  • 3
  • 17
  • For the `try-except` above, do you need to explicitly write a `continue`? – ShanZhengYang Feb 11 '16 at 15:06
  • No continues necessary - but my post has missing newlines. You can't see the indents which you need. This [SO answer](http://stackoverflow.com/a/730778/5870826) shows it properly formatted: – Keith Brodie Feb 11 '16 at 20:56