标签:保存 str div 输出 auth json 分隔线 import 字典
将字典以字符串形式保存进文本:
1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 info = { 4 ‘name‘:‘csy‘, 5 ‘age‘:‘31‘ 6 } 7 f = open("test.text","w") 8 f.write(str(info)) 9 f.close()
当再次打开的时候,输出会是个字符串:
1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 f = open("test.text","r") 4 data = f.read() 5 f.close() 6 print(data)
输出:
{‘age‘: ‘31‘, ‘name‘: ‘csy‘}
##################################华丽的分隔线#################################
(1)可使用eval方式再次将字符串转换为字典:
1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 f = open("test.text","r") 4 data = eval(f.read()) 5 f.close() 6 print(data) 7 print(data[‘age‘]) 8 print(data[‘name‘])
输出:
{‘name‘: ‘csy‘, ‘age‘: ‘31‘}
31
csy
##################################华丽的分隔线#################################
(2)常用方法是使用Json再次将字符串转换为字典,首先保存时用json.dumps()方法:
1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 import json 4 info = { 5 ‘name‘:‘csy‘, 6 ‘age‘:‘31‘, 7 ‘job‘:‘IT‘ 8 } 9 f = open("test.text","w") 10 f.write(json.dumps(info)) 11 f.close()
反序列化:
1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 import json 4 f = open("test.text","r") 5 data = json.loads(f.read()) 6 f.close() 7 print(data) 8 print(data[‘age‘]) 9 print(data[‘name‘],data[‘job‘])
输出:
{‘job‘: ‘IT‘, ‘name‘: ‘csy‘, ‘age‘: ‘31‘}
31
csy IT
标签:保存 str div 输出 auth json 分隔线 import 字典
原文地址:http://www.cnblogs.com/csy113/p/7634473.html