Pythonでのファイルとjsonオブジェクトの読み取りと書き込み

目次

1つは、ファイルの読み取りと書き込みです 

2、jsonオブジェクトの読み取りと書き込み


 

1つは、ファイルの読み取りと書き込みです 

filename = "./output/data.txt"

# 文件写入
with open(filename, 'w', encoding='utf-8') as myfile:
    myfile.write("你好,Python!\n")
    myfile.write("hello Python!\n")

# 文件读出
with open(filename, 'r', encoding='utf-8') as myfile:
    content = myfile.read()
    print(content)

2、jsonオブジェクトの読み取りと書き込み

import json

filename = "output/data.json"

mydata = {
    "user": {
        "username": "lijiang", 
        "password":123, 
    },
    "age": 22
}

# json对象写入
with open(filename, 'w', encoding='utf-8') as myfile:
    json.dump(mydata, myfile, indent=4)

# json对象读出
with open(filename, 'r', encoding='utf-8') as myfile:
    myjson = json.load(myfile)
    print(myjson)

 

おすすめ

転載: blog.csdn.net/qq_40323256/article/details/112202138