Python - Numpy 报错:FileNotFoundError: [Errno 2] No such file or directory

4

我有这段代码:

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'

我该如何解决这个问题?文件夹没有被创建......谢谢。

请尝试使用 os.path.isfile - Stack
1个回答

6

看起来你正在尝试将文件写入一个不存在的目录中。

在调用np.save()之前,尝试使用os.mkdir创建要保存的目录。

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


谢谢,但我有一个问题:为什么我看不到创建的文件夹? - maicol07
另外,如果我使用cx_freeze MSI安装程序在没有Python的计算机上安装它,它会给我WinError 3。 - maicol07
1
我不完全确定您所说的“see the folder”是什么意思,您是指在资源管理器中吗? 另外,关于“WinError 3”,如果您将Python程序编译成适用于Windows机器的.exe文件,则我相信任何基于Python的.exe文件都需要在计算机上安装Python,虽然我可能错了。 - RHSmith159
2
算了,我解决了:os.path.expanduser(r'~\Documents\School Life Diary') - maicol07
1
啊,好棒的修复!另外,我已经有一段时间没有为Windows制作Python可执行文件了,但我认为有一些编译成exe的方法,这样用户就不需要安装Python或使用的模块。这个答案将是你开始的好地方:https://dev59.com/PG035IYBdhLWcg3wYO51 - RHSmith159
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接