python 文件不存在時才能寫入,讀寫模式xt


想向一個文件中寫入數據,但是前提必須是這個文件在文件系統上不存在。也就是不允許覆蓋已存在的文件內容。

可以在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 函數庫中都是沒有這個模式的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM