转载来源:https://blog.csdn.net/lwbeyond/article/details/61198555
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) 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()
原文地址:https://www.cnblogs.com/qiaoqiao123321/p/8986758.html