Pay attention to the WeChat public account: (New Programmer Tutorial)
Download python notes for free, as well as java full-stage notes, front-end vue notes, etc., and regularly share programming learning platforms
(1) Use the json conversion in the import json package
[1] Save the dictionary-type --transfer-string into the file
import json
import os
file_init=open("admin.txt",mode="w",encoding="utf-8")
admin_dict={}
admin_dict["name"]=name
admin_dict["pwd"]=pwd
# print("字典",admin_dict)
# print("josn:",json.dumps(admin_dict))#json.dumps()用于将dict类型的数据转成str
file_init.write(json.dumps(admin_dict)) # json.dumps()用于将dict类型的数据转成str
【2】Convert jsonStr—to—dictionary
user_login_file = open("user.txt", mode="r", encoding="utf-8")
file_data=user_login_file.read()
user_read_dict = json.loads(file_data) #将jsonStr—转—字典
(2) Use the built-in functions that come with python to convert
[1] Save the dictionary-type --transfer-string into the file
import json
import os
file_init=open("admin.txt",mode="w",encoding="utf-8")
admin_dict={}
admin_dict["name"]=name
admin_dict["pwd"]=pwd
file_init.write(str(admin_dict)) #str()类型的数据转成str
【2】
Eval():
1Evaluate the string as a valid expression and return the result
2 A simple understanding is that the code inside is run directly (without preventing the injection of malicious code)
user_login_file = open("user.txt", mode="r", encoding="utf-8")
file_data=user_login_file.read()
# {2}和我的写法不同处
user_read_dict = eval(file_data)