Python how to store the data as json format file

 

A, json based storage module, reading data

names_writer.py

1 import json
2 
3 names = ['joker','joe','nacy','timi']
4 
5 filename='names.json'
6 with open(filename,'w') as file_obj:
7     json.dump(names,file_obj)

Explanation: We first import json module, and then create a list of names, line 5 we specify the name of the list to which you want to store the file. .Json usually use the extension to indicate the data file is stored in json format. Line 6 we open the file in write mode, line 7 we use the function json.dump () The name list is stored in a file names.json. This program does not print the console after executing anything, in fact, we can also print a similar statement following tips for success, but I omitted here.

We look at the folder where the file names_writer.py names.json file (tips: If the folder does not exist in this file is automatically created and written data), names.json contents are as follows:

["joker", "joe", "nacy", "timi"]

Here read this json file written procedure:

names_reader.py

1 import json
2 
3 
4 
5 filename='names.json'
6 with open(filename) as file_obj:
7     names = json.load(file_obj)
8     
9 print(names)

Print Console as follows:

Explanation: reading operation, the same modules need to import json, line 6 the code we open the file using the read mode, line 7, the json.load we use the function () to read the information names.json, and stores the variable names, and finally print it. When we print the results and store the same. json file you can share it with other people, other people can read the data therein, and this is a simple way to share data between a programming.

We have to solve the specific problems with the above knowledge. 

Problem : Write a program that prompts the user to enter his favorite fruit, and use json.dump () will store the fruit name to a file. Then write a program that reads the values from the file and prints the message "I know your favorite fruit! It 's _____.".

favorite.py

1 import json
2 
3 filename = "favorite_fruit.json"
4 
5 fruit = input( "What is your favorite fruit?")
6 with open(filename,'w') as file_obj:
7     json.dump(fruit,file_obj)

Print Console as follows:

reader_favorite.py

1 import json
2 
3 file_name = "favorite_fruit.json"
4 with open(file_name) as file_obj:
5     fruit = json.load(file_obj)
6 
7 print("I know your favorite fruit !  It's " + fruit)

Print Console as follows:

You can see the program is running normally. Description of the process we write according to the normal operation running is no problem. Next, we reconstruct this example, to make it better.

 

 

  After stepping out, everything can not learn the first, but we must learn financial management, and it will become a lifelong habit.

 

Reproduced in: https: //www.cnblogs.com/tizer/p/11067098.html

Guess you like

Origin blog.csdn.net/weixin_34252090/article/details/93786031