Python对已不存在的文件执行写入操作

问题

我们想将数据写入到一个文件中,但只在该文件已不存在文件系统中时才这么做。

解决方案

这个问题可以通过使用open()函数中鲜为人知的x模式替代常见的w模式来解决。示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> with open('somefile.txt', 'wt') as f:
... f.write('hello world\n')
...
12
>>> with open('somefile.txt', 'xt') as f:
... f.write('hello world\n')
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile.txt'
>>>
>>> import os
>>> os.remove('somefile.txt')
>>> with open('somefile.txt', 'xt') as f:
... f.write('hello world\n')
...
12
>>>

如果文件是二进制模式的,那么用xb模式代替xt即可。

讨论

本文中的示例以一种非常优雅的方式解决了一个常会在写文件时遇到的问题(即,意外地覆盖了某个已存在的文件)。另一种解决方案是首先像这样检查文件是否已存在:

1
2
3
4
5
6
7
8
9
>>> import os
>>> if not os.path.exists('somefile.txt'):
... with open('somefile.txt', 'wt') as f:
... f.write('hello world\n')
... else:
... print('File already exists!')
...
File already exists!
>>>

很明显,使用x模式更加简单直接。需要注意的是,x模式是Python 3中对open()函数的扩展。在早期的Python版本或者在Python的实现中用到的底层C函数库里都不存在这样的模式。

大师兄 wechat
欢迎关注我的微信公众号:Python大师兄