in the file, the default is only the string, is not the dictionary, binary this special type of data, if you want to save the dictionary format data into the file, you need to convert the data type
data = {"Name": "Xiaoming", "Age": 22}
f = open ("Test.txt", "r+", encoding= "Utf-8")
F.write (data)//Convert data to String type
F.close ()
If you read the data now, the string must not be used in the form of data["Name") to tune the value, so you also need to convert the string to a dictionary format
f = open ("Test.txt", "r+", encoding= "Utf-8")
data = eval (F.read ())//tips, using eval to convert a string to a dictionary format
F.close ()
Print (data["Name"])
Although the above approach also enables serialization and deserialization, it is recommended to use the standard way to manipulate
Import JSON
data = {"Name": "Xiaoming", "Age": 22}
Print (Type json.dumps (data))///Here is a test to see what type of data after dumps
f = open ("Test.txt", "W", encoding= "Utf-8")
F.write (Json.dumps (data))//using Json.dumps for serialization
F.close ()
Next look at the JSON deserialization
Import JSON
f = open ("Test.txt", "R", encoding= "Utf-8")
data = Json.loads (F.read ())//deserialization with Json.loads
F.close ()
Print (data["Name"])
Small summary: JSON can only handle some simple data formats, such as dictionaries, lists, strings, etc., but JSON is common in all languages, such as Python programs and Java programs to interact with, you need to use JSON to convert.
So if you want to deal with some complex data, such as receiving a function in a dictionary, take a look at the example:
Import pickle//pickle module needs to be imported
def hello (name):
Print ("name", name)
data = {"Name": "Xiaoming", "Age": $, "AA": Hello}//The memory address of the function as the value of the dictionary, compared to a complex data type
f = open ("Test.txt", "WB")//because the data after pickle is binary type, so open mode to use "B"
F.write (Pickle.dumps (data))
F.close ()
Print (Type pickle.dumps (data)))//data type after last print Pickle.dumps
Pickle deserialization
Import Pickle
def hello (name):
Print ("name", name)
f = open ("Test.txt", "RB")
data = Pickle.loads (F.read ())//pickle.loads for deserialization
F.close ()
Print (data["AA"] ("BBB"))//Here is the parameter of the function
Small summary: Pickle can only be used in Python language, and cannot be used across languages.
Python3 Data Serialization Tool JSON