Reading and writing of files and json objects in Python

table of Contents

One, file read and write 

Two, json object read and write


 

One, file read and write 

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)

Two, json object read and write

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)

 

Guess you like

Origin blog.csdn.net/qq_40323256/article/details/112202138