W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
你想像一個文件中寫入數(shù)據,但是前提必須是這個文件在文件系統(tǒng)上不存在。也就是不允許覆蓋已存在的文件內容。
可以在 open()
函數(shù)中使用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
討論 這一小節(jié)演示了在寫文件時通常會遇到的一個問題的完美解決方案(不小心覆蓋一個已存在的文件)。 一個替代方案是先測試這個文件是否存在,像下面這樣:
>>> 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()
函數(shù)特有的擴展。在Python的舊版本或者是Python實現(xiàn)的底層C函數(shù)庫中都是沒有這個模式的。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: