昨天看了地獄廚房
今天受不了下班就跑去買牛排來回家烤!起!來!
颱風感覺逼近中
雙十連假一級警報!!!
!()[https://media.giphy.com/media/26tPlltsuA89RwYww/giphy.gif]
好的開始練習昨天檔案的讀取和儲存
儲存檔案
# 儲存檔案
# 開啟
file=open("data.txt", mode="w")
# 存入內容
file.write("Hello File")
# 關閉
file.close()
測試再跑一次
修改file.write("Hello File666")
文件會被覆蓋
另外中文部份open需設定 encoding
file=open("data.txt", mode="w", encoding="utf-8")
file.write("開文件\n關文件")
file.close()
最後存資料最佳示範
with open("data2.txt", mode="w", encoding="utf-8") as filename:
filename.write("開文件\n關文件")
讀取檔案(檔案需存在)
# 讀取
with open("data2.txt", mode="r", encoding="utf-8") as filename:
data=filename.read()
print("A:"+data)
讀取檔案
# 每一行數字,每行讀取後累加
with open("data3.txt", mode="w", encoding="utf-8") as filename:
filename.write("5\n3")
ssum=0
with open("data3.txt", mode="r", encoding="utf-8") as filename:
for line in filename:
ssum+=int(line)
print(ssum)
json格式讀取
# json格式讀取
import json
with open("config.json", mode="r", encoding="utf-8") as filename:
data=json.load(filename)
print(data)
print(data["name"])
回寫
# json格式讀取
import json
with open("config.json", mode="r", encoding="utf-8") as filename:
data=json.load(filename)
print(data)
print("name="+data["name"])
# 更新資料
data["name"]="name123"
# 將更新data 回寫檔案
with open("config.json", mode="w") as file:
json.dump(data, file)