2017-08-16 92 views
-1

我有这样的代码:蟒蛇 - numpy的FileNotFoundError:[错误2]没有这样的文件或目录

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' 

我怎样才能解决这个问题?该文件夹未创建...

感谢

+0

尝试使用'os.path.isfile' – Stack

回答

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

+0

谢谢,但我有一个问题:为什么我看不到创建的文件夹? –

+0

此外,如果我将它安装在没有Python的计算机上,使用cx_freeze MSI安装程序,它给了我WinError 3 –

+0

我不完全确定'你看到文件夹'是什么意思,你的意思是在资源管理器中? 关于'WinError 3',如果你正在编译python程序到windows机器的.exe中,我很确定任何基于python的.exe都需要在机器上安装python,我可以虽然 – RHSmith159

相关问题