Python - 文字檔案的讀取跟存取


1.文字檔的儲存


 file = open("data.txt", mode="w", encoding="utf-8") 
 file.write("測試中文")
 file.close()

 #使用with,就不用file.close()
 with open("data.txt", mode="w", encoding="utf-8") as file:
     file.write("測試中文")

2.讀取文字檔

    with open("data.txt", mode="r", encoding="utf-8") as file:
        data = file.read()
        print(data)

3.一行一行的讀取檔案


# 文字內容都是數字、我要做數字加總
sum = 0
with open("data.txt", mode="r", encoding="utf-8") as file:
    for line in file:
        sum += int(line)

print(f"Sum:{sum}")

4.讀取Json格式的檔案

import json
# 從檔案中讀取json資料,放入變數data裡面
with open("config.json", mode="r", encoding="utf-8") as file:
    data = json.load(file)  # 讀進來是一個Dictionary


# print(data)
# 注意、Key有分大小寫
print("Name", data["Name"])
print("Version", data["Version"])

5.修改Json檔案內容

data["Name"] = "New Name"
data["New Attribute"] = "New Attribute"
# 把最新的資料複寫回檔案中
with open("config.json", mode="w", encoding="utf-8") as file:
    json.dump(data, file)
#Python 基礎






Related Posts

【單元測試的藝術】Chap 1: 單元測試基礎

【單元測試的藝術】Chap 1: 單元測試基礎

Go Web 程式設計入門教學:語法基礎之流程控制(flow control)篇

Go Web 程式設計入門教學:語法基礎之流程控制(flow control)篇

[04] Renderless Component

[04] Renderless Component






Comments