2017-08-16 54 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

相關問題