[Python] json file reading and writing

Read json

import json
json_file = ''
with open(json_file, 'r', encoding='utf8') as fp:
    json_data = json.load(fp)

Write json

import json
json_file = '1.json'
dict1 = [{
    
    'name': 'Tom', 'age': 10}, {
    
    'name': 'Marry', 'age': 18}]
with open(json_file,'w',encoding='utf8')as fp:
    json.dump(dict1,fp,ensure_ascii=False)

r: read only (the file with r must exist first)
r+: read and write, and will not create non-existent files. If you write to the file directly, start writing from the top and overwrite the content at this position before. If you read and write later, the content will be appended to the end of the file.

w: Can only write. If the entire file does not exist, it will be created.
w+: Read and write. If the file exists, the entire file will be overwritten if it does not exist, then it will be created // to be closed before writing is completed

a: Can only write. Add content from the bottom of the file, create it if it does not exist.
a+: Read and write. Read content from the top of the file, add content from the bottom of the file, create if it does not exist

reference:

  1. python reads json file
  2. Python open function's understanding of w+ r+ read and write operations (turn)

Guess you like

Origin blog.csdn.net/weixin_38705903/article/details/107643642