python - numpy FileNotFoundError:[Errno 2]没有这样的文件或目录

时间:2017-08-16 13:41:16

标签: python file numpy operating-system directory

我有这段代码:

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)

但他给我的错误是:

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

我该如何解决这个问题?该文件夹尚未创建...

由于

1 个答案:

答案 0 :(得分:1)

看起来您正在尝试将文件写入不存在的目录。

在调用os.mkdir

之前,尝试使用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)

编辑:

创建新目录时,如果要创建多个深度的新目录结构,例如如果不存在这些文件夹,请创建level1/level2/level3,使用os.mkdirs代替os.mkdiros.mkdirs是递归的,将构造字符串中的所有目录。