【问题标题】:python - numpy FileNotFoundError: [Errno 2] No such file or directorypython - numpy FileNotFoundError: [Errno 2] 没有这样的文件或目录
【发布时间】:2018-01-24 16:41:51
【问题描述】:

我有这个代码:

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

标签: python file numpy operating-system directory


【解决方案1】:

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

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

【讨论】:

  • 谢谢,但我有一个问题:为什么我看不到创建的文件夹?
  • 另外,如果我用 cx_freeze MSI 安装程序将它安装在没有 Python 的计算机上,它给了我 WinError 3
  • 我不完全确定您所说的“查看文件夹”是什么意思,您是指在资源管理器中吗?另外,关于WinError 3,如果您将python程序编译为Windows机器的.exe,我很确定任何基于python的.exe都需要在机器上安装python,我可能错了虽然
  • 没关系,解决了:os.path.expanduser(r'~\Documents\School Life Diary')
  • 啊!另外,自从我为 Windows 制作 python exe 文件以来已经有一段时间了,但我认为有一些方法可以编译为 exe,这样用户就不需要安装 python 或使用的模块,这个答案将是一个很好的起点给你:https://stackoverflow.com/questions/5458048/how-to-make-a-python-script-standalone-executable-to-run-without-any-dependency
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 2021-09-14
  • 1970-01-01
相关资源
最近更新 更多