zoukankan      html  css  js  c++  java
  • python3 pickle, json

    pickle 有dump ,dumps ,load,loads等方法。区别在于dumps不会写入到文件。

     1 import pickle
     2 
     3 string = ['a', 2341, 'adsf']
     4 
     5 p_str= pickle.dumps(string)
     6 print(p_str)
     7 l_str = pickle.loads(p_str)
     8 print(l_str)
     9 
    10 p_str1 = 'This is a test!'
    11 with open('d:/python/pydev/day3/src/p.pkl', 'wb') as file:
    12     pickle.dump(p_str1, file)
    13 
    14 with open('d:/python/pydev/day3/src/p.pkl', 'rb' ) as file1:  
    15     l_file = pickle.load(file1)
    16 
    17 print(l_file)
    pickle

    结果如下:

    b'x80x03]qx00(Xx01x00x00x00aqx01M% Xx04x00x00x00adsfqx02e.'
    ['a', 2341, 'adsf']
    This is a test!

    '''
    The file argument must have a write() method that accepts a single bytes argument.
    It can thus be an on-disk file opened for binary writing
    '''

    注意:pickle以二进制处理,所以文件打开方式应该加上b, 如'wb'.'rb'如果仅以w方式打开则会报错,这里可能理解有误,奇怪的是json用wb会报错,而w则正常。

     1 import json
     2 
     3 string = ['a', 2341, 'adsf']
     4 
     5 p_str= json.dumps(string)
     6 print(p_str)
     7 l_str = json.loads(p_str)
     8 print(l_str)
     9 
    10 p_str1 = 'This is a test!'
    11 with open('d:/python/pydev/day3/src/p.pkl', 'w') as file:
    12     json.dump(p_str1, file)
    13 
    14 with open('d:/python/pydev/day3/src/p.pkl', 'r' ) as file1:  
    15     l_file = json.load(file1)
    16 
    17 print(l_file)
    json

    运行结果:

    ["a", 2341, "adsf"]
    ['a', 2341, 'adsf']
    This is a test!

    pickle是python特有的,而json支持语言很多。另外json dump的结果是可以直接读的,pickle则不行。

  • 相关阅读:
    gdb调试
    go pipeline
    Go的Timer
    goconvey
    购物
    Go的可行测试
    可能会停止一段时间的更新
    一些blog
    linux全套 | Python开发平台_Ubuntu | 15
    Python基础 | 配置pip镜像源 | 01
  • 原文地址:https://www.cnblogs.com/Andy963/p/5322065.html
Copyright © 2011-2022 走看看