Python 当目录不存在时,os.mkdir(path) 返回 OSError
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18973418/
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
os.mkdir(path) returns OSError when directory does not exist
提问by Quanquan Liu
I am calling os.mkdir
to create a folder with a certain set of generated data. However, even though the path I specified has not been created, the os.mkdir(path)
raises an OSError that the path already exists.
我正在调用os.mkdir
以创建一个包含特定生成数据集的文件夹。但是,即使我指定的路径尚未创建,也会os.mkdir(path)
引发路径已存在的 OSError。
For example, I call:
例如,我调用:
os.mkdir(test)
This call results in OSError: [Errno 17] File exists: 'test'
even though I don't have a test directory or a file named test anywhere.
OSError: [Errno 17] File exists: 'test'
即使我在任何地方都没有测试目录或名为 test 的文件,此调用也会产生结果。
NOTE: the actual path name I use is not "test" but something more obscure that I'm sure is not named anywhere.
注意:我使用的实际路径名不是“test”,而是一些更晦涩的东西,我确信没有在任何地方命名。
Help, please?
请帮忙?
采纳答案by Chris Johnson
Greg's answer is correct but doesn't go far enough. OSError
has sub-error conditions, and you don't want to suppress them all every time. It's prudent to trap just expectedOS errors.
格雷格的回答是正确的,但还远远不够。 OSError
有子错误条件,你不想每次都抑制它们。捕获预期的操作系统错误是明智的。
Do additional checking before you decide to suppress the exception, like this:
在您决定抑制异常之前进行额外的检查,如下所示:
import errno
import os
try:
os.mkdir(dirname)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
pass
You probably don't want to suppress errno.EACCES
(Permission denied), errno.ENOSPC
(No space left on device), errno.EROFS
(Read-only file system) etc. Or maybe you do want to -- but that needs to be a conscious decision based on the specific logic of what you're building.
您可能不想抑制errno.EACCES
(权限被拒绝)、errno.ENOSPC
(设备上没有剩余空间)、errno.EROFS
(只读文件系统)等。或者您确实想要——但这需要根据具体情况做出有意识的决定你正在构建的逻辑。
Greg's code suppresses all OS errors; that's unsafe just like except Exception
is unsafe.
Greg 的代码抑制了所有操作系统错误;那是不安全的,就像except Exception
是不安全的一样。
回答by Greg
I don't know the specifics of your file system. But if you really want to get around this maybe use a try/except clause?
我不知道你的文件系统的细节。但是,如果您真的想解决这个问题,可以使用 try/except 子句吗?
try:
os.mkdir(test)
except OSError:
print "test already exists"
You can always do some kind of debugging in the meanwhile.
在此期间,您始终可以进行某种调试。
回答by CT Zhu
You have a file there with the name test
. You can't make a directory with that exact same name.
您在那里有一个名为test
. 您不能创建具有完全相同名称的目录。
回答by lordkain
Just check if the path exist. if not create it
只需检查路径是否存在。如果不创建它
if not os.path.exists(test):
os.makedirs(test)
回答by Tabraiz Ali
Maybe there's a hidden folder named test in that directory. Manually check if it exists.
也许该目录中有一个名为 test 的隐藏文件夹。手动检查是否存在。
ls -a
ls -a
Create the file only if it doesn't exist.
仅当文件不存在时才创建该文件。
if not os.path.exists(test):
os.makedirs(test)
回答by Omer Dagan
Happened to me on Windows, maybe this is the case:
在 Windows 上发生在我身上,也许是这样:
Like you I was trying to :
像你一样,我试图:
os.mkdir(dirname)
and got OSError: [Errno 17] File exists: '<dirname>'
.
When I ran:
并得到了OSError: [Errno 17] File exists: '<dirname>'
。当我跑:
os.path.exists(dirname)
I got false, and it drove me mad for a while :)
我弄错了,这让我发疯了一段时间:)
The problem was: In a certain window I was at the specific directory. Even though it did not exists at that time (I removed it from linux). The solution was to close that window \ navigate to somewhere else. Shameful, I know ...
问题是:在某个窗口中,我在特定目录中。即使当时它不存在(我从 linux 中删除了它)。解决方案是关闭该窗口\导航到其他地方。可耻,我知道...
回答by Anupam Bera
I also faced the same problem, specially, when the string 'test' contains the multiple directory name. So when 'test' contains the single directory -
我也遇到了同样的问题,特别是当字符串 'test' 包含多个目录名称时。因此,当“test”包含单个目录时 -
if not os.path.exists(test):
try:
os.makedir(test)
except:
raise OSError("Can't create destination directory (%s)!" % (test))
If the 'test' contains multiple directory like '\dir1\dir2' then -
如果 'test' 包含多个目录,如 '\dir1\dir2' 那么 -
if not os.path.exists(test):
try:
os.makedirs(test)
except:
raise OSError("Can't create destination directory (%s)!" % (test))
回答by 1''
In Python 3.2 and above, you can use:
在 Python 3.2 及更高版本中,您可以使用:
os.makedirs(path, exist_ok=True)
os.makedirs(path, exist_ok=True)
to avoid getting an exception if the directory already exists. This will still raise an exception if path
exists and is not a directory.
以避免在目录已经存在时出现异常。如果path
存在并且不是目录,这仍然会引发异常。
回答by Ahsan aslam
For python 2.7
对于python 2.7
from distutils.dir_util import mkpath
mkpath(path)
回答by Georg
Simple answer that does not require any additional import, does not suppress errors such as "permission denied", "no space left on device" etc., yet accepts that the directory may already exist:
不需要任何额外导入的简单答案,不会抑制诸如“权限被拒绝”、“设备上没有剩余空间”等错误,但接受目录可能已经存在:
import os
try:
os.mkdir(dirname)
except FileExistsError :
pass
except :
raise