Python how to store the data as json format file (continued)

The previous example of tinkering, the two programs into one, if you store the user's favorite fruit on display it, or prompt the user to enter his favorite fruit and store it in a file.

favorite.py

 1 import json
 2 
 3 filename = "favorite_fruit.json"
 4 
 5 def greet_user():
 6     """问候用户,并指出他喜欢的水果"""
 7     fruit = get_saved_fruit()
 8     if fruit:
 9         print("I know your favorite fruit !  It's " + fruit)
10     else:
11         fruit = save_user_new_fruit()
12         print("I know your favorite fruit !  It's "+ Fruit)
 13 is  
14  
15      
16  
. 17  DEF save_user_new_fruit ():
 18 is      "" " prompts the user favorite fruit " "" 
. 19      Fruit = INPUT ( " ? What IS your Favorite Fruit " )
 20 is      with Open (filename, ' W ' ) file_obj AS:
 21          json.dump (file_obj, fruit)
 22      return fruit
 23  
24-  DEF get_saved_fruit ():
 25      "" " If you store the user's favorite fruit, you get it " "" 
26      the try :
 27         with open(filename) as  file_obj:
28             fruit = json.load(file_obj)
29     except FileNotFoundError:
30         return None
31     else:
32         return fruit
33         
34 greet_user()

Explanation: After optimizing the code, each function only needs to perform a single task, which is more in line with the design process

After the first run the program the console as follows:

If we are the first run, as shown below

It allows users to enter favorite fruit and then respond to user his favorite fruit.

And after the run, as shown:

Because the program after the first run will have a user's favorite fruit into the json file.

So it will not prompt the user.

 

Guess you like

Origin www.cnblogs.com/tizer/p/11070173.html