Trying to use open(filename, 'w' ) gives IOError: [Errno 2] No such file or directory if directory doesn't exist

余生颓废 提交于 2019-11-30 06:39:13

You are correct in surmising that the parent directory for the file must exist in order for open to succeed. The simple way to deal with this is to make a call to os.makedirs.

From the documentation:

os.makedirs(path[, mode])

Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.

So your code might run something like this:

filename = ...
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
    os.makedirs(dirname)
with open(filename, 'w'):
    ...
paxdiablo

If you try to create a file in a directory that doesn't exist, you will get that error.

You need to ensure the directory exists first. You can do that with os.makedirs() as per this answer.

Alternately, you could check if the file exists before opening it with:

os.path.exists (afile)

Which will either say True or False, depending on whether it exists.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!