Learn More →
基本語法
檔案物件=open(檔案路徑,mode=開啟模式)
開啟模式
讀取全部文字
檔案物件.read()
一次讀取一行
for 變數 in檔案物件:
從檔案依序讀取每行文字到變數中
(for迴圈一行一行讀取)
讀取Json格式
import json
讀取到的資料=jaon.load(檔案物件)
寫入文字
檔案物件.write(字串)
寫入換行符號
檔案物件.write("這是範例文字\n")
寫入jaon格式
import json
jason.dump(要寫入的資料,檔案物件)
基本語法
檔案物件.close()
with open(檔案路徑,mode=開放模式)as 檔案物件:讀取或寫入檔案的程式
(以上區塊會自動 安全地關閉檔案 不需要寫close)
with open("data.txt", mode="r", encoding="utf-8") as file:
data=file.read()
print(data)
測試中文
好棒棒
sum=0
with open("data.txt", mode="r", encoding="utf-8") as file:
for line in file: #一行一行讀取
sum=sum+int(line)
print(sum)
8
建立新檔案config.json
{"name":"My Name",
"version":"1.2.5"
}
使用Json格式 讀取資料
import json
with open("config.json, mode="r") as file:
data=json.load(file)
print(data) #data是一個字典資料
print("name:", data["name"])
print("version:", data["version"])
name: My Name
version:1.2.5
從檔案中讀取Json資料,放入變數data裡修改資料
import json
with open("config.json, mode="r") as file:
data=json.load(file)
print(data) #data是一個字典資料
data["name"]="New Name" #修改變數中的資料
把最新的檔案複寫回檔案中 寫入是W
with open("config.json, mode="w") as file:
json.dump(data, file)
另一個資料的檔案會被複寫 如下
{"name":"New Name", "version":"1.2.5"}