python - 专门处理文件存在异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20790580/
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
python - specifically handle file exists exception
提问by cogitoergosum
I have come across examples in this forum where a specific error around files and directories is handled by testing the errnovalue in OSError(or IOErrorthese days ?). For example, some discussion here - Python's "open()" throws different errors for "file not found" - how to handle both exceptions?. But, I think, that is not the right way. After all, a FileExistsErrorexists specifically to avoid having to worry about errno.
我在这个论坛中遇到过一些例子,其中通过测试(或最近?)中的errno值来处理文件和目录周围的特定错误。例如,这里的一些讨论——Python 的“open()”为“找不到文件”抛出不同的错误——如何处理这两种异常?. 但是,我认为,这不是正确的方法。毕竟, a 的存在是为了避免不必担心.OSErrorIOErrorFileExistsErrorerrno
The following attempt didn't work as I get an error for the token FileExistsError.
以下尝试无效,因为我收到了 token 错误FileExistsError。
try:
os.mkdir(folderPath)
except FileExistsError:
print 'Directory not created.'
How do you check for this and similar other errors specifically ?
您如何专门检查此错误和类似的其他错误?
采纳答案by falsetru
According to the code print ..., it seems like you're using Python 2.x. FileExistsErrorwas added in Python 3.3; You can't use FileExistsError.
根据代码print ...,您似乎使用的是 Python 2.x。FileExistsError在 Python 3.3 中添加;你不能使用FileExistsError.
Use errno.EEXIST:
使用errno.EEXIST:
import os
import errno
try:
os.mkdir(folderPath)
except OSError as e:
if e.errno == errno.EEXIST:
print('Directory not created.')
else:
raise
回答by Tom Hale
Here's an example of dealing with a race condition when trying to atomically overwrite an existing symlink:
这是尝试以原子方式覆盖现有符号链接时处理竞争条件的示例:
# os.symlink requires that the target does NOT exist.
# Avoid race condition of file creation between mktemp and symlink:
while True:
temp_pathname = tempfile.mktemp()
try:
os.symlink(target, temp_pathname)
break # Success, exit loop
except FileExistsError:
time.sleep(0.001) # Prevent high load in pathological conditions
except:
raise
os.replace(temp_pathname, link_name)

