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

南笙酒味 提交于 2021-01-24 07:04:11

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/45715236/python-numpy-filenotfounderror-errno-2-no-such-file-or-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!