《Python Cookbook 3rd》笔记(5.5):文件不存在才能写入
生活随笔
收集整理的這篇文章主要介紹了
《Python Cookbook 3rd》笔记(5.5):文件不存在才能写入
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文件不存在才能寫入
問題
你想像一個文件中寫入數據,但是前提必須是這個文件在文件系統上不存在。也就是不允許覆蓋已存在的文件內容。
解法
可以在 open() 函數中使用 x 模式來代替 w 模式的方法來解決這個問題。比如:
>>> with open('somefile', 'wt') as f: ... f.write('Hello\n') ... >>> with open('somefile', 'xt') as f: # 'x' : open for exclusive creation, failing if the file already exists ... 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 函數庫中都是沒有這個模式的。
總結
以上是生活随笔為你收集整理的《Python Cookbook 3rd》笔记(5.5):文件不存在才能写入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《Python Cookbook 3rd
- 下一篇: 《Python Cookbook 3rd