When the user closes the program , You almost always keep the information they provide ; A simple way is to use modules JSON To store data . Store in memory , That is, the data content is stored locally , Read and write data
modular JSON So you can put simple Python Dump the data structure to a file ( Save locally ), And load the data in the file when the program runs again . You can still use it JSON stay Python Sharing data between programs .
Examples : When the user logs in , Store the user name and password entered by the user , The next time the user logs in , Call according to the user name JSON Password in storage , Realize the user's automatic login or remember the password .
#JSON The data format is not Python A dedicated , This allows you to take JSON The data stored in the format is shared with people using other programming languages .
Use JSON Module before , The module needs to be imported import json
(1)JSON Storage ( write in )
import json
numbers = [2, 3, 5, 7, 11, 13] # Store a wide variety of content , It can be any type
filename = 'numbers.json' # File path The general file object type is json file
with open(filename, 'w') as f_obj:# The open mode is writable
json.dump(numbers, f_obj) # Storage file
【 grammar 】:
json.dump( Data content to be stored , File objects that can be used to store data ( File to be opened ))
(2)JSON Content reading
import json
filename = 'numbers.json' # File path The general file object type is json file
with open(filename) as f_obj:
numbers = json.load(f_obj) # Read the file
print(numbers)
【 grammar 】
json.load( File object to be read ( File to be opened ))
(3) Save and read user generated data ==》( The content is stored locally , Easy to read )
For user generated data , Use json It's good to keep them , Because if you don't store it in some way , When the program stops running, the user's information will be lost . Let's take a look at such an example : When the user runs the program for the first time Be prompted to enter your name , So you can remember him when you run the program again .
import json
# If the user name was previously stored , Just load it
# otherwise , Just prompt the user for a user name and store it
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)# Load data
except FileNotFoundError:
username = input("What is your name? ")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj) # Store the data
print("We'll remember you when you come back, " + username + "!")
else:# If exception is caught , Execute statement segment
print("Welcome back, " + username + "!")