C 文字檔案處理
文字檔案函數
| 開啟模式 | 描述 |
|---|---|
"r" | 讀取文字檔案內容。若檔案不存在便會出現運行時錯誤。 |
"x" | 創建檔案。若檔案已存在便會出現運行時錯誤。 |
"w" | 開啟檔案並覆寫內容。若檔案不存在便會創建該檔案。 |
"a" | 開啟檔案並追加內容。若檔案不存在便會創建該檔案。 |
- 開啟文字檔案:
f = open("datafile.txt", "r") - 關閉文字檔案:
f.close() - 檢查文字檔案是否存在:
import os os.path.exists("targetfile.txt") - 刪除文字檔案:
import os os.remove("targetfile.txt")
讀取文字檔案
- 讀取全部內容(作為字串傳回):
f.read() - 讀取第一行內容(作為字串傳回):
f.readline() - 讀取全部內容(每行作為列表的一個項目傳回):
f.readlines()
寫入文字檔案
f.write("Write here.")
字串處理 (String Manipulation)
檢索字串
- 從索引 0 開始檢索:
the_string.find("is") - 從指定索引開始檢索:
the_string.find("is", 3)
分拆字串
- 以空格為定界符號分拆:
the_string.split() - 以指定的字符為定界符號分拆:
the_string.split("#")
替換字串
- 將所有出現的指定字串替換:
the_string.replace("two", "2") - 只替換指定的次數:
the_string.replace("three", "3", 1)
Last updated on