[英]In Python when writing to a file how can you make sure the data is saved on one line?
[英]How to make sure a file exists or can be created before writing to it in Python?
我正在寫一個函數,我想讓它touch
一個文件,以便我可以寫入該文件。 如果該文件不存在,我將收到錯誤。 我該怎么說呢?
只需打開文件進行寫入,如果文件不存在,則會創建(假設您有適當的權限寫入該位置)。
f = open('some_file_that_might_not_exist.txt', 'w')
f.write(data)
如果無法打開文件進行寫入,則會出現IOError
。
根據文檔,os.utime()的作用類似於touch,如果你給它作為時間參數,例如:
os.utime("test_file", None)
當我測試它時(在Linux和更高版本的Windows上),我發現test_file必須已經存在。 YMMV在其他操作系統上。
如果您確實想要在文件不存在時引發錯誤,則可以使用
import os
if not os.access('file'):
#raise error
f = open('file')
#etc.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.