问题
I have this code:
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)
But the error that he gave me is:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Maicol\\Documents\\School Life Diary\\settings.npy'
How can I solve this? The folder isn't created...
Thanks
回答1:
Looks like you're trying to write a file to a directory that doesn't exist.
Try using os.mkdir
to create the directory to save into before calling 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)
EDIT:
When creating your new directory, if you're creating a new directory structure more than one level deep, e.g. creating level1/level2/level3
where none of those folders exist, use os.mkdirs
instead of os.mkdir
.
os.mkdirs
is recursive and will construct all of the directories in the string.
来源:https://stackoverflow.com/questions/45715236/python-numpy-filenotfounderror-errno-2-no-such-file-or-directory