Python批量修改資料夾內所有json檔案中部分內容

右介發表於2017-12-07
#coding=utf-8 

import os
import json

#獲取目標資料夾的路徑
filedir = os.getcwd()+'/ceshi'
#獲取資料夾中的檔名稱列表  
filenames=os.listdir(filedir)
#遍歷檔名
for filename in filenames:
    filepath = filedir+'/'+filename
    print filepath

    after = []
    # 開啟檔案取出資料並修改,然後存入變數
    with open(filepath, 'rb') as f:
        data = json.load(f)
        print type(data)
        for zidian in data:
            if zidian["conference_date"] == "":
                zidian["conference_date"] = "0001-01-01T00:00:00Z"
            if zidian["publication_date"] == "":
                zidian["publication_date"] = "0001-01-01T00:00:00Z"
        after = data

    # 開啟檔案並覆蓋寫入修改後內容
    with open(filepath, 'wb') as f:
        data = json.dump(after, f)

 

相關文章