而"x"表示以独创模式打开文件,如果文件存在,则引发FileExistsError。
使用此模式,您的代码将简单地编写为
try:
with open("fname", "x") as fout:
#Work with your open file
except FileExistsError:
# Your error handling goes here
以前的代码可能是
try:
with open("fname", "x") as fout:
#Work with your open file
except FileExistsError:
# Your error handling goes here