Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - numpy FileNotFoundError: [Errno 2] No such file or directory [duplicate]

I have this code:

import os.path
import numpy as np
homedir=os.path.expanduser("~")
pathset=os.path.join(homedir,"\Documents\School Life Diary\settings.npy")
if not(os.path.exists(pathset)):
    ds={"ORE_MAX_GIORNATA":5}
    np.save(pathset, ds)

But the error that he gave me is:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Maicol\\Documents\\School Life Diary\\settings.npy'

How can I solve this? The folder isn't created...

Thanks

like image 515
maicol07 Avatar asked Sep 07 '25 03:09

maicol07


1 Answers

Looks like you're trying to write a file to a directory that doesn't exist.

Try using os.mkdir to create the directory to save into before calling np.save()

import os
import numpy as np


# filename for the file you want to save
output_filename = "settings.npy"

homedir = os.path.expanduser("~")

# construct the directory string
pathset = os.path.join(homedir, "\Documents\School Life Diary")

# check the directory does not exist
if not(os.path.exists(pathset)):

    # create the directory you want to save to
    os.mkdir(pathset)

    ds = {"ORE_MAX_GIORNATA": 5}

    # write the file in the new directory
    np.save(os.path.join(pathset, output_filename), ds)

EDIT:

When creating your new directory, if you're creating a new directory structure more than one level deep, e.g. creating level1/level2/level3 where none of those folders exist, use os.mkdirs instead of os.mkdir. os.mkdirs is recursive and will construct all of the directories in the string.

like image 68
RHSmith159 Avatar answered Sep 08 '25 23:09

RHSmith159