文件不存在才能写入

可以在 open() 函数中使用 x 模式来代替 w 模式的方法来解决这个问题。
不用再去判断文件是否存在了。
比如:

>>> import os
>>> if not os.path.exists('somefile'):
...     with open('somefile', 'wt') as f:
...         f.write('Hello
')
... else:
...     print('File already exists!')
...
File already exists!
>>>

wt可以换成xt
wb可以换成xb

原文地址:https://www.cnblogs.com/c-x-a/p/10699304.html