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 基礎






你可能感興趣的文章

[FE201] webpack 讓你把各種資源包在一起(基本介紹篇)

[FE201] webpack 讓你把各種資源包在一起(基本介紹篇)

D25_ ALG101-Unit 5-LIOJ 1046, 1034

D25_ ALG101-Unit 5-LIOJ 1046, 1034

Node.js 和Node.js REPL 關係

Node.js 和Node.js REPL 關係






留言討論