码迷,mamicode.com
首页 > 其他好文 > 详细

文件不存在才能写入

时间:2019-04-13 00:44:25      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:int   with open   print   文件   模式   file   函数   \n   open   

可以在 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

文件不存在才能写入

标签:int   with open   print   文件   模式   file   函数   \n   open   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!