问题
向一个文件中写入数据,但是前提必须是这个文件在文件系统上不存在。 也就是不允许覆盖已存在的文件内容。
解决方案
可以在 open()
函数中使用 x
模式来代替 w
模式的方法来解决这个问题。比如:
with open('/Users/xz/test/cook.txt', 'w') as f:
f.write('Hello Python !')
f.close()
with open('/Users/xz/test/cook.txt', 'x') as f:
f.write('Hello Python !')
f.close()
Traceback (most recent call last):
File "/Users/xz/Documents/sublime/cookbook/cook-5.5.py", line 5, in <module>
with open('/Users/xz/test/cook.txt', 'x') as f:
FileExistsError: [Errno 17] File exists: '/Users/xz/test/cook.txt'
如果文件是二进制的,使用 xb
来代替 xt
讨论
x
模式是一个Python3
对 open()
函数特有的扩展。 在Python的旧版本或者是Python实现的底层C函数库中都是没有这个模式的。
网友评论