Try   HackMD

13. Python 文字檔案的讀取和儲存 By 彭彭

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

讀取 儲存文字檔案

檔案操作流程

  1. 開啟檔案
  2. 讀取或寫入
  3. 關閉檔案

1. 開啟檔案

基本語法
檔案物件=open(檔案路徑,mode=開啟模式)

2. 讀取或寫入

開啟模式

  • 讀取模式- r
  • 寫入模式- w
  • 讀寫模式- r+

3.讀取檔案

  • 讀取全部文字
    檔案物件.read()

  • 一次讀取一行
    for 變數 in檔案物件:
    從檔案依序讀取每行文字到變數中
    (for迴圈一行一行讀取)

  • 讀取Json格式
    import json
    讀取到的資料=jaon.load(檔案物件)

4.寫入檔案 (儲存檔案)

  • 寫入文字
    檔案物件.write(字串)

  • 寫入換行符號
    檔案物件.write("這是範例文字\n")

  • 寫入jaon格式
    import json
    jason.dump(要寫入的資料,檔案物件)

5.關閉檔案

基本語法
檔案物件.close()


最佳實務

with open(檔案路徑,mode=開放模式)as 檔案物件:讀取或寫入檔案的程式
(以上區塊會自動 安全地關閉檔案 不需要寫close)

Practice

一:儲存檔案

  1. 開起檔案 讀取或寫入 儲存檔案
    file=open("data.txt", mode="w") #開啟
    file.write("Hello File") #操作
    file.close() #關閉
  • 處理中文問題 指定utf-8編碼
    file=open("data.txt", mode="w", encoding="utf-8") #開啟
    file.write("測試中文\n好棒棒") #操作
    file.close() #關閉
  1. 最佳實務示範
    with open("data.txt", mode="w",encoding="utf-8") as file:
    file.write("測試中文\n好棒棒")

二:讀取檔案(讀取已經存在的檔案)

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

測試中文
好棒棒

  1. 讀取檔案數字 做加法
    把檔案中的數字資料,一行一行讀取出來,並計算總合

sum=0
with open("data.txt", mode="r", encoding="utf-8") as file:
for line in file: #一行一行讀取
sum=sum+int(line)
print(sum)

8

三:使用Json格式讀取 複寫檔案

  1. 建立新檔案config.json
    {"name":"My Name",
    "version":"1.2.5"
    }

  2. 使用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

  1. 從檔案中讀取Json資料,放入變數data裡修改資料
    import json
    with open("config.json, mode="r") as file:
    data=json.load(file)
    print(data) #data是一個字典資料
    data["name"]="New Name" #修改變數中的資料

  2. 把最新的檔案複寫回檔案中 寫入是W
    with open("config.json, mode="w") as file:
    json.dump(data, file)

另一個資料的檔案會被複寫 如下
{"name":"New Name", "version":"1.2.5"}