open 檔案相關應用

檔案讀寫

參考:https://steam.oxxostudio.tw/category/python/basic/builtin-open.html#google_vignette

讀取JSON檔案

import json
with open('DemoData/demoData.json') as f:
  demo_data = json.load(f)

寫出檔案

def test_output_to_json(content: str, path='Output/test.json'):
    f = open(path, 'w')
    f.write(content)
    f.close()

寫出JSON檔案

import json
import os

file_path = '檔案路徑'
data = {'A':'a'}

with open(file_path, 'w', encoding='utf-8') as f:  # 預設是使用系統編碼,直接指定更保險
    # case1 - 轉格式,格式不合可能會跳錯,建議外補個TryCatch
    json.dump(data, f, indent=4, ensure_ascii=False)
    # ensure_ascii用於解決json直接將中文顯示為「\u1234」的模樣
    
    # case2 - 當一般文字檔案寫出
    f.write(str(data))

參考:https://blog.csdn.net/wbdxz/article/details/81950877

Last updated