一、通过io读取数据,StringIO函数操作str
1.StringIO:从io模块导入,创建StringIO实例,通过StringIO实例操作str
'''
from io import StringIO
str_io = StringIO()
str_io.write('hello')
print('str_io is:',str_io.getvalue())
str_io = StringIO('hello\nworld\nwelcome!')
while True:
line = str_io.readline()
if line =='':
break
print('line is:', line)
'''
通过io读取数据,StringIO函数操作str
1.StringIO:从io模块导入,创建StringIO实例,
通过StringIO实例操作str
'''
fromioimportStringIO
str_io = StringIO()
str_io.write('hello')
print('str_io is:',str_io.getvalue())
str_io = StringIO('hello\nworld\nwelcome!')
while True:
line = str_io.readline()
ifline =='':
break
print('line is:',line)
序列化和反序列化
1.在python中,可以用pickle模块实现序列化:pickle.dump(obj,file)
2.反序列化:pickle.load(file对象) 或bytes = pickle.dumps(file)
pickle.loads(bytes)
import pickle
# 1
d =dict(name='xiaoming',num=2010)
print(pickle.dumps(d))
try:
f_name =open('C:/Users/HouYushan/Desktop/dump.txt','wb')
pickle.dump(d,f_name)
# 2
bytes = pickle.dumps(d)
result = pickle.loads(bytes)
print(result)
bytes1 = pickle.dumps(d)
result1 = pickle.loads(bytes1)
print(result1)
finally:
f_name.close()
'''序列化和反序列化
1.在python中,可以用pickle模块实现序列化:pickle.dump(obj,file)
2.反序列化:pickle.load(file对象)或bytes = pickle.dumps(file)
pickle.loads(bytes)
'''
importpickle
# 1
d =dict(name='xiaoming',num=2010)
print(pickle.dumps(d))
try:
f_name =open('C:/Users/HouYushan/Desktop/dump.txt','wb')
pickle.dump(d,f_name)
# 2
bytes = pickle.dumps(d)
result = pickle.loads(bytes)
print(result)
bytes1 = pickle.dumps(d)
result1 = pickle.loads(bytes1)
print(result1)
finally:
f_name.close()
'''
JSON序列化与反序列化
使用jsion模块对JSON数据进行编码解码。json.dumps():对数据进行编码;json.loads():对数据进行解码。
json.dump()对文件进行操作:写入JSON数据;json.load()对文件进行操作:读取JSON数据'''
import json
data = {'name':'xiaoming','num':1000}
json_data = json.dumps(data)
print('python_data:',data)
print('json_data:',json_data)
python_data = json.loads(json_data)
print('解码成的python数据:',python_data)
print('name:',python_data['name'])
print('num:',python_data['num'])
with open('C:/Users/HouYushan/Desktop/dump.txt','w')as f:
json.dump(data,f)
with open('C:/Users/HouYushan/Desktop/dump.txt','r')as f:
print(json.load(f))
'''
JSON序列化与反序列化
1.使用jsion模块对JSON数据进行编码解码。
json.dumps():对数据进行编码;
json.loads():对数据进行解码。
2.json.dump()对文件进行操作:写入JSON数据;
json.load()对文件进行操作:读取JSON数据
'''
importjson
data = {'name':'xiaoming','num':1000}
json_data = json.dumps(data)
print('python_data:',data)
print('json_data:',json_data)
python_data = json.loads(json_data)
print('解码成的python数据:',python_data)
print('name:',python_data['name'])
print('num:',python_data['num'])
withopen('C:/Users/HouYushan/Desktop/dump.txt','w')asf:
json.dump(data,f)
withopen('C:/Users/HouYushan/Desktop/dump.txt','r')asf:
print(json.load(f))
领取专属 10元无门槛券
私享最新 技术干货