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

问题描述 投票:0回答:1

我有这个代码:

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'

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

谢谢

python file numpy operating-system directory
1个回答
6
投票

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

在调用

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.mkdir
os.mkdirs
是递归的,将构造字符串中的所有目录。

© www.soinside.com 2019 - 2024. All rights reserved.