Python 尝试使用 open(filename, 'w' ) 会导致 IOError: [Errno 2] 如果目录不存在,则没有这样的文件或目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18758673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to use open(filename, 'w' ) gives IOError: [Errno 2] No such file or directory if directory doesn't exist
提问by gonzalimator
I am trying to create and write to a text file using Python. I have searched and cannot find a solution/reason for this error.
我正在尝试使用 Python 创建和写入文本文件。我已经搜索过但找不到此错误的解决方案/原因。
Here's the code that doesn't work:
这是不起作用的代码:
afile = 'D:\temp\test.txt'
outFile = open(afile, 'w' )
outFile.write('Test.')
outFile.close()
# Error: 2
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# IOError: [Errno 2] No such file or directory: 'D:\temp\test.txt' #
Most answers I found related to the slashes in the path, so...
我发现的大多数答案都与路径中的斜杠有关,所以......
I tried 'D:/temp/test.txt' and got an error.
I tried r'D:\temp\test.txt' and got an error.
When I try to create a file at the root of D:/ I have success.
当我尝试在 D:/ 的根目录创建一个文件时,我成功了。
'D:/test.txt' works.
'D:\test.txt' works.
r'D:\test.txt' works.
It seems that I can't create the directory path I would like while trying to create the file. What is the correct method for creating files at a specific path with Python on Windows(7)? Am I misunderstanding what open() can do? Does it create directories if they don't exist or do I need to explicitly create the directory path before I use open() in 'write' mode to create a file?
似乎我在尝试创建文件时无法创建我想要的目录路径。在 Windows(7) 上使用 Python 在特定路径创建文件的正确方法是什么?我误解了 open() 可以做什么吗?如果目录不存在,它是否会创建目录,或者我是否需要在“写入”模式下使用 open() 创建文件之前显式创建目录路径?
采纳答案by David Heffernan
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
.
您推测文件的父目录必须存在才能open
成功,这是正确的。解决这个问题的简单方法是调用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.
os.makedirs(路径[,模式])
递归目录创建功能。像
mkdir()
,但是使所有需要的中间级目录都包含叶目录。
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'):
...
回答by 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.
回答by aMoon
Alternately, you could check if the file exists before opening it with:
或者,您可以在打开文件之前检查文件是否存在:
os.path.exists (afile)
os.path.exists (afile)
Which will either say True or False, depending on whether it exists.
哪个会说 True 或 False,这取决于它是否存在。