Heim >Backend-Entwicklung >Python-Tutorial >Python中 pickle有什么意义,pickle了再恢复?
Python初级
对象1 -- 序列化 -> 字节串 -- 反序列化 -> 对象2所以很多人并不知道为什么要序列化。
<code class="language-pycon"><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">pickle</span>
<span class="gp">>>> </span><span class="n">data</span> <span class="o">=</span> <span class="p">{</span>
<span class="gp">... </span> <span class="s">'1'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="gp">... </span> <span class="mf">23.45</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span>
<span class="gp">... </span> <span class="k">print</span><span class="p">:</span> <span class="nb">set</span><span class="p">(),</span>
<span class="gp">... </span> <span class="n">b</span><span class="s">'hello'</span><span class="p">:</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">],</span>
<span class="gp">... </span><span class="p">}</span>
<span class="gp">>>> </span><span class="n">pickle</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="go">b'\x80\x03}q\x00(G@7s33333cbuiltins\nstr\nq\x01cbuiltins\nprint\nq\x02cbuiltins\nset\nq\x03]q\x04\x85q\x05Rq\x06X\x01\x00\x00\x001q\x07\x88C\x05helloq\x08]q\t(K\x00K\x00K\x00eu.'</span>
<span class="gp">>>> </span><span class="n">pickle</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">_</span><span class="p">)</span>
<span class="go">{23.45: <class>, <built-in function print>: set(), '1': True, b'hello': [0, 0, 0]}</built-in></class></span>
</code>
玩过游戏吗?知道 Save/Load 吗?
python自带的file函数只能存储和读取字符串格式的数据.