想向一個文件中寫入數據,但是前提必須是這個文件在文件系統上不存在。也就是不允許覆蓋已存在的文件內容。
可以在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'
>>>
先測試這個文件是否存在
>>> 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 函數庫中都是沒有這個模式的。
