前言
這一次來教大家如何在Python中開啟檔案,來進行處理!
python2 檔案
1. 開啟檔案 open
變數名稱 = open("檔案名稱","flag")
變數名稱.mode
2. 讀取檔案 read + seek
-
若檔案讀取過,記得注意目前檔案指針是否有回到檔案頭
myfile=open("檔名","r")
myfile.read()
myfile.read(索引)
myfile.seek(0)
myfile.readline()
myfile.readlines()
3. 寫入檔案 write + close
-
須注意open的flag可能會造成寫入去覆蓋原本資料
-
記得關閉檔案(close),並關閉python
myfile=open("檔名","w")
myfile.write("加入之內容")
myfile.writelines([1,2,3] or (1,2,3))
myfile.close
範例
- open函式使用flag=w系列時,若無檔案會創建新的檔案
- 當使用write後沒close,會造成檔案沒儲存
- 使用close關閉檔案,並關閉python輸入框
- 寫入一整個陣列(但是呈現還是如字串)
4. 關閉檔案 close + with-as
- with-as:自動使用close,不需要擔心無關閉檔案
with open("檔名","flag") as 變數名稱:
變數名稱.read or 變數名稱.write