Python物件序列化寫入檔案物件
阿新 • • 發佈:2019-01-09
1.建立Python檔案物件的讀寫模式(r,w模式)與建立Java輸入輸出流;
FileInputStream inputStream=new FileInputStream(new File("E:\\workspace\\tmpfile\\farrago.txt"));
FileOutputStream outputStream=new FileOutputStream(new File("E:\\workspace\\tmpfile\\outagainb.txt"));
2.序列化Python物件,序列化成字串如toJson和序列化成二進位制;
3.向檔案物件中寫入序列化物件。
PS:有的序列化包,有方便的方法直接將序列化和寫入過程合二為一。numpy的save和load感覺就是序列化而已,那麼其必要性不大了?
import umsgpack import pickle import numpy as np """ 1.建立Python檔案物件的讀寫模式(r,w模式)與建立Java輸入輸出流; FileInputStream inputStream=new FileInputStream(new File("E:\\workspace\\tmpfile\\farrago.txt")); FileOutputStream outputStream=new FileOutputStream(new File("E:\\workspace\\tmpfile\\outagainb.txt")); 2.序列化Python物件,序列化成字串如toJson和序列化成二進位制; 3.向檔案物件中寫入序列化物件。 PS:有的序列化包,有方便的方法直接將序列化和寫入過程合二為一。numpy的save和load感覺就是序列化而已,那麼其必要性不大了? """ with open('test0.bin', 'wb') as f: rs = umsgpack.packb({u"compact": True, u"schema": 0}) f.write(rs) with open('test0.bin', 'rb') as f: print(umsgpack.unpackb(f.read())) print("_+"*20) with open('test.bin', 'wb') as f: print(umsgpack.pack({u"compact": True, u"schema": 0}, f)) print(umsgpack.pack([1,2,3], f)) with open('test.bin', 'rb') as f: print(umsgpack.unpack(f)) print(umsgpack.unpack(f)) print("_+"*20) with open('test2.bin', 'wb') as f: rs = pickle.dumps({u"compact": True, u"schema": 0}) f.write(rs) print(pickle.loads(rs)) with open('test2.bin', 'rb') as f: print(pickle.load(f)) print("_+"*20) with open('test3.bin', 'wb') as f: pickle.dump({u"compact": True, u"schema": 0},f) with open('test3.bin', 'rb') as f: print(pickle.load(f)) print("_+="*20) with open('test4.bin', 'wb') as f: """有沒有覺得numpy的save與load就是個二進位制序列化協議""" np.save(f, 'abc') np.save(f, np.arange(10)) with open('test4.bin', 'rb') as f: print(np.load(f)) print(np.load(f)) print("888" * 20)