轉載來源:
https://blog.csdn.net/lwbeyond/article/details/61198555
123.json
[ { "Country Name": "Arab World", "Country Code": "ARB", "Year": "1960", "Value": "96388069" }, { "Country Name": "Arab World", "Country Code": "ARB", "Year": "1961", "Value": "98882541.4" } ]
repositories.json
{ "fontFamily": "微軟雅黑", "fontSize": 12, "BaseSettings":{ "font":1, "size":2 } }
讀取json寫入txt
import json import os def opera_file1(): document = open("testfile.txt", "w+") # print("文件名: ", document.name) document.write("這是我創建的第一個測試文件!\nwelcome!") print(document.tell()) # 輸出當前指針位置 document.seek(os.SEEK_SET) # 設置指針回到文件最初 context = document.read() print(context) document.close() def opera_file2(str_content): with open("testfile.txt", "w+") as f: f.write(str_content) # 讀取 {字典} 類型的 json 文件: # 設置以utf-8解碼模式讀取文件,encoding參數必須設置,否則默認以gbk模式讀取文件,當文件中包含中文時,會報錯 def json_dict(): f = open("repositories.json", encoding='utf-8') setting = json.load(f) # 注意多重結構的讀取語法 family = setting['BaseSettings']['font'] style = setting['fontFamily'] print(family) print(style) # 讀取【列表】格式的 json 文件 # 將數據加載到一個列表中 def json_list(): filename = 'C:/Users/Administrator/Desktop/123.json' # 注意點1:絕對路徑的寫法 temp_content = '' with open(filename, encoding='utf-8') as f: pop_data = json.load(f) # 打印每個國家2010年的人口數量 for pop_dict in pop_data: country_name = pop_dict['Country Name'] population = pop_dict['Value'] temp_content += country_name + ' : ' + population + " ;\n" # print(country_name + ": " + population) opera_file2(temp_content) # print(temp_content) # 打印出json最終的字符串 json_list() # json_dict()