"Python" stores data

Source: Internet
Author: User

Many programs require users to enter some kind of information, such as allowing users to store game preferences or provide visual data, no matter what focus, the program to store data, then how to store it?

The JSON (JavaScript Object Notation) format was originally developed for JavaScript, but then became a common format that was used by many languages, including Python.

Using Json.dump () and Json.loan ()

1.josn.dump () storing data

Syntax: Json.dump (store data, file name)

Import= [1,2,3,4,5,6'testdump.json'with open (file_name,  'w') as File_obj:    json.dump (numbers,file_obj)

We can see the file in the folder

2.json.laod () reading data

Syntax: json.load (file name)

Here is our program to read the Testdump.json content of the data file

Import'testdump.json'withOpen (file_name) as file_obj:    = json.load (file_obj) Print (numbers)

This is a simple way to share data between programs

Saving and reading user-generated data

For user-generated data, it is helpful to use JSON to save them, because if they are not stored in some way, the user's data will be lost when the program stops running.

Import= input ("what isyour name? ") "  'username.json'with open (filename,'w' as file_obj:    json.dump (username,file_obj)    print("we'll Remeber when you come back," + username+"! ")

Operation Result:

We prompt for the user name and store it in a variable, then we call Json.dump () and pass the user name and a file object to him, storing the user name in the file.

We are writing a program that sends greetings to the user whose name is stored

Import'username.json'withOpen (file_name) as f_obj:    =  Json.load (f_obj)    print("Welcome back,"+username+" ! ")

Operation Result:

We combine two programs into one program. When this program runs, we will try to get the user name from the file Username.json, so we first write a try code block that tries to recover the user name. When the file does not exist, we are prompted to enter the user name in except and store it in the Username.json file so that it can be obtained when the program runs again.

ImportJSON#loads a user name if it was previously stored, or prompts the user to enter a user namefile_name ='Username.json'Try: With open (file_name) as F_obj:username=json.load (f_obj)exceptFilenotfounderror:username= Input ("What is your name?") with open (file_name,'W') as F_obj:json.dump (username,f_obj)Print("we'll remeber you if you're come back,"+username+"!")Else:    Print("Welcome back,"+username+"!")

The first run output of this program is as follows:

Otherwise, the output is as follows:

Refactoring

You often encounter situations where the code works correctly, but can be further improved by dividing the code into a series of functions that do the work, which is called refactoring

ImportJSONdefGreet_user ():" "greet the user and indicate its name" "file_name='Username.json'    Try: With open (file_name) as F_obj:username=json.load (f_obj)exceptFilenotfounderror:username= Input ("What is your name?") with open (file_name,'W') as F_obj:json.dump (username,f_obj)Print("we'll remeber you if you're come back,"+username+"!")    Else:       Print("Welcome back,"+username+"!")#calling FunctionsGreet_user ()

Perhaps some people think that the above program performs too many tasks, we do not want it to do so many tasks, we first get the stored user name of the code to move to another function:

"Take action when a file exists"

ImportJSONdefget_stored_username ():" "If the user name is stored, get it" "file_name='Username.json'    Try: With open (file_name) as F_obj:username=json.load (f_obj)exceptFilenotfounderror:returnNoneElse:       returnusernamedefGreet_user ():" "greet the user and indicate its name" "username=Get_stored_username ()ifUsername:Print("Welcome back,"+ Username +"!")    Else: Username= Input ("What is your name?") file_name='Username.json'with open (file_name,'W') as F_obj:json.dump (username, f_obj)Print("we'll remeber you if you're come back,"+ Username +"!")#calling FunctionsGreet_user ()

The new function get_stored_username () target is very clear, if the file stores the user name, the function gets and returns it, if the file does not exist, this function returns NONE, this is a good way: The function either returns the expected value, or returns none.

"Extract actions that prompt user input when no user name is stored"

The above program can also continue to be optimized to extract another piece of code from Greet_user (): Put the code that prompts the user for input without storing the user name in a separate function

ImportJSONdefget_stored_username ():" "If the user name is stored, get it" "file_name='Username.json'    Try: With open (file_name) as F_obj:username=json.load (f_obj)exceptFilenotfounderror:returnNoneElse:       returnusernamedefget_new_username ():" "Prompt user to enter user name" "username= Input ("What is your name?") file_name='Username.json'with open (file_name,'W') as F_obj:json.dump (username,f_obj)returnusernamedefGreet_user ():" "greet the user and indicate its name" "username=Get_stored_username ()ifUsername:Print("Welcome back,"+ Username +"!")    Else: Username=Get_new_username ()Print("we'll remeber you if you're come back,"+ Username +"!")#calling FunctionsGreet_user ()

This version is the final version, and each function performs a single and clear task.

"Python" stores data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.