首页 > 解决方案 > Pickle:存储变量的内容

问题描述

我将模块泡菜保存在我的目录中。现在,我想将变量 ie Arpan 存储在一个名为 spdict.data 的创建文件中,因此,当我输入如下代码时:

    import pickle
    Arpan = "My name is Arpan"
    fh = open("spdict.data","w")
    pickle.dump(Arpan,fh)
    fh.close()

我希望变量 Arpan 被存储,但我收到以下错误。

回溯(最后一次调用):文件“C:\Users\Home\AppData\Local\Programs\Python\Python36-32\IDLE scripts for bioinfo book\File handling\test1 reading fasta.py”,第 173 行,在 pickle .dump(Arpan,fh) TypeError: write() argument must be str, not bytes

另外,当我进入程序

import pickle
Arpan = {"One":1,"Two":2,"Three":3}
fh = open("spdict.data","w")
pickle.dump(Arpan,fh)
fh.close()

然后,还会出现以下错误:

回溯(最后一次调用):文件“C:\Users\Home\AppData\Local\Programs\Python\Python36-32\IDLE scripts for bioinfo book\File handling\test1 reading fasta.py”,第 173 行,在 pickle .dump(Arpan,fh) TypeError: write() argument must be str, not bytes

请帮忙..我的python版本是3.6.4

标签: pythonpython-3.x

解决方案


编写泡菜时,打开文件进行二进制写入。

fh = open("spdict.data", "wb")

推荐阅读