国内做批发的网站/b站视频推广app
Camp时在python2的编码上坑了不少。
python2字符串类型只有两种:
str类型:b'xxx'即是str类型, 是编码后的类型,len()按字节计算
unicode类型:len()按unicode字符计算
python2打开文件读取的字符串是str类型,无encoding参数
python2下读写文件建议使用 codecs包
codecs.open, codecs.write可以指定编码
python3的编码
python3字符串类型分两种:
str类型:u'xxx'即是str类型,是未编码的unicode。注意与python2的区分
bytes类型:编码后的类型
python3打开文件有encoding参数, 可以按指定编码方式读入,读取为str类型(即未编码的unicode)字符串
Python 2 将 strings 处理为原生的 bytes 类型,而不是 unicode,
Python 3 所有的 strings 均是 unicode 类型。
utf-8编码兼容ascii编码,asscii编码后的字符与utf-8编码后的字符结果相同
========================================================================================
python存储读取数据
数组
importnumpy
a= [1, 2, 3, 4, 5]
numpy.save('arr1.npy', a)
b= numpy.load('arr1.npy')#################
importnumpy
a= [1, 2, 3, 4, 5]
numpy.savetxt('arr.txt',a)
b= numpy.loadtxt('arr.txt')#################
importnumpy
a= [1,2,3,4,5]
a.tofile('arr1.bin',)
b= numpy.fromfile("arr1.bin",dtype=**)
字典
#使用pickle模块将数据对象保存到文件
importpickle
data1= {'a': [1, 2.0, 3, 4+6j],'b': ('string', u'Unicode string'),'c': None}
selfref_list= [1, 2, 3]
selfref_list.append(selfref_list)
output= open('data.pkl', 'wb')#Pickle dictionary using protocol 0.
pickle.dump(data1, output)#Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)
output.close()
#使用pickle模块从文件中重构python对象
importpprint, pickle
pkl_file= open('data.pkl', 'rb')
data1=pickle.load(pkl_file)
pprint.pprint(data1)
data2=pickle.load(pkl_file)
pprint.pprint(data2)
pkl_file.close()