5.5 文件�存在�能写入¶

问题¶

你想�一个文件中写入数�,但是��必须是这个文件在文件系统上�存在。 也就是��许覆盖已存在的文件内容。

解决方案¶

�以在 open() 函数中使用 x 模��代替 w 模�的方法�解决这个问题。比如:

>>> with open('somefile', 'wt') as f:
...     f.write('Hello\n')
...
>>> with open('somefile', 'xt') as f:
...     f.write('Hello\n')
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
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\n')
... else:
...     print('File already exists!')
...
File already exists!
>>>

显而易�,使用x文件模�更加简�。�注�的是x模�是一个Python3对 open() 函数特有的扩展。 在Python的旧版本或者是Python实现的底层C函数库中都是没有这个模�的。