How to use np.save to save files in different directory in python?

14,530

From the (DOCS):

file : file, str, or pathlib.Path

File or filename to which the data is saved. If file is a file-object, then the filename is unchanged. If file is a string or Path, a .npy extension will be appended to the file name if it does not already have one.

This states that if the filename has a directory (ie: Path), it will be stored there. So something like this should do what you need:

import os
np.save(os.path.join('Check', 'train_set'), training)
Share:
14,530
sara
Author by

sara

Updated on June 17, 2022

Comments

  • sara
    sara over 1 year

    I want to save training in a different folder named Check. How can I save this using np.save command? I read about np.save command from documentation but it doesn't describe how to save it in different directory.

    sample = np.arange(100).reshape(10,10)
    split = 0.7
    index = int(floor(len(sample)*split))
    training = sample[:index]
    np.save("Check"+'train_set.npy',training)
    
  • sara
    sara over 6 years
    How I can save it in documents? should I mention x=os.path.join('Documents' , 'Check') and then np.save(x , '/train_set' ,training)
  • Stephen Rauch
    Stephen Rauch over 6 years
    What OS are you using?
  • sara
    sara over 6 years
    I'm using ubuntu 14.04
  • Stephen Rauch
    Stephen Rauch over 6 years
    So the os.path.join() is used build the paths. It adds them together in a way that will work on any OS. But what is not mentioned is where the path starts. If the path does not start at a specific place, then it is relative to what ever the current directory is when the program runs. On Ubuntu I think Documents is in your home directory, so to start in Documnets, than can be built with: docs_dir=os.path.expanduser('~/Documents'). Then np.save(os.path.join(docs_dir, 'Check', 'train_set'), ...