标签:文件的 while open pre tuple 字节 dict 报错 user
# 文件存取时,遇到的矛盾.
# 数据 读取出来时,反转不回去.
# 凡是数据通过网络传出去最终的格式必须bytes
# 序列化模块作用:
# 将一组数据结构转化成特殊的序列(特殊的字符串,bytes)并且还可以反转回去.
# json 模块: 是所有语言公认的一种序列.最最常用的
# 所以支持的python数据结构有限: int str bool dict list(tuple),None,float
# pickle模块: 只能python语言中使用的,序列化模块:
# 支持python所有的数据类型以及对象.
import json
# dumps,loads 主要用于网络传输,可以用于文件的存取.
# dic = {'username': '太白', 'password': 123,'status': False}
# ret=json.dumps(dic)
# print(ret,type(ret))
# ret_dict = json.loads(ret)
# print(ret,type(ret_dict))
# 特殊的参数ensure_ascii确定是不是使用ascii码 sort_keys我可以给这个字典排序
# dic = {'username': '太白', 'password': 123,'status': False}
# ret = json.dumps(dic,ensure_ascii=False,sort_keys=True)
# print(ret,type(ret))
# dump load: 单个数据的存取文件.
# import json
# dic = {'username': '太白', 'password': 123,'status': False}
# with open('jsonlx1.json',encoding='utf-8',mode='w') as f1:
# json.dump(dic,f1)
#
# with open('jsonlx1.json',encoding='utf-8') as f1:
# dic1 = json.load(f1)
# print(dic1,type(dic1))
# 多个数据如何存储到一个文件中 必须换行 不然读取时不识别 会报错?
# import json
# dic1 = {'username': '太白', 'password': 123,'status': False}
# dic2 = {'username': 'alex', 'password': 123,'status': False}
# dic3 = {'username': 'ly', 'password': 123,'status': False}
# with open('jsonmore.json',encoding='utf-8',mode='a') as f1:
# f1.write(f'{json.dumps(dic1)}\n{json.dumps(dic2)}\n{json.dumps(dic3)}')
#
# with open('jsonmore.json',encoding='utf-8') as f1:
# for line in f1:
# ret = json.loads(line)
# print(ret,type(ret))
# pickle
import pickle # dumps,loads 只能是网络传输#只能python语言中使用的,序列化模块 支持python所有的数据类型以及对象.
# dumps,loads 只能是网络传输 直接转化为字节
# l1 = ['wusir', '太白', '小黑', 666]
# ret = pickle.dumps(l1)
# print(ret)
# l2 = pickle.loads(ret)
# print(l2,type(l2))
# dump load 数据结构存取文件.
import pickle
# l1 = ['wusir', '太白', '小黑', 666]
# with open('pickle练习.pickle',mode='wb') as f1:
# pickle.dump(l1,f1)
# with open('pickle练习.pickle', mode='rb') as f1:
# ret = pickle.load(f1)
# print(ret,type(ret))
# 多个数据写入文件
# l1 = ['wusir', '太白', '小黑1', 666]
# l2 = ['wusir', '太白', '小黑2', 666]
# l3 = ['wusir', '太白', '小黑3', 666]
# with open('pickle练习1.pickle',mode='wb') as f1:
# # pickle.dump(l1,f1)
# # pickle.dump(l2,f1)
# # pickle.dump(l3,f1)
#
# with open('pickle练习1.pickle', mode='rb') as f1:
# # ret1 = pickle.load(f1)
# # ret2 = pickle.load(f1)
# # ret3 = pickle.load(f1)
# # print(ret1,ret2,ret3)
# while 1:
# try:
# ret1 = pickle.load(f1)
# print(ret1)
# except Exception:
# break
#
标签:文件的 while open pre tuple 字节 dict 报错 user
原文地址:https://www.cnblogs.com/saoqiang/p/12177117.html