你想像一个文件中写入数据,但是前提必须是这个文件在文件系统上不存在。也就是不允许覆盖已存在的文件内容。
可以在 open() 函数中使用 x 模式来代替 w 模式的方法来解决这个问题。比如:
>>> with open('somefile', 'wt') as f:
... f.write('Hello
')
...
>>> with open('somefile', 'xt') as f:
... f.write('Hello
')
...
Traceback (most recent call last):
File "", line 1, in
FileExistsError: [Errno 17] File exists: 'somefile'
>>>
如果文件是二进制的,使用 xb 来代替 xt
以上演示了在写文件时通常会遇到的一个问题的完美解决方案 (不小心覆盖一个已存在的文件)。一个替代方案是先测试这个文件是否存在,像下面这样:
>>> 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!
>>>
显而易见,使用 x 文件模式更加简单。要注意的是 x 模式是一个 Python3 对 open() 函数特有的扩展。在 Python 的旧版本或者是 Python 实现的底层 C 函数库中都是没有这个模式的。
------
页面更新:2024-04-20
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号