文件不存在才能写入

mac2022-06-30  16

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

转载于:https://www.cnblogs.com/c-x-a/p/10699304.html

最新回复(0)