文件不存在才能写入

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

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

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

posted @ 2019-04-12 23:30  公众号python学习开发  阅读(177)  评论(0编辑  收藏  举报