zoukankan      html  css  js  c++  java
  • Python对象序列化写入文件对象

     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)
    

  • 相关阅读:
    WCF学习笔记之传输安全
    JavaScript –type
    详解android的号码匹配
    list和用vector区别(Vector相当于是数组,读写快,插入慢)
    拒绝收购邀请,三年专注开发,开源的私有云盘“迷你云”(十人团队在三年时间里靠自筹资金专注开发出来的作品)
    无功不受禄
    如何判断是否安装了VC RUNTIME
    GExpert 1.38 实验版含经典代码格式工具 Berlin 编译版
    初始化IoC容器(Spring源码阅读)
    JavaScript函数绑定
  • 原文地址:https://www.cnblogs.com/wdmx/p/10242242.html
Copyright © 2011-2022 走看看