Python - 使用pickle时发生类型错误 - 如何正确使用它

标签 python file pickle

我想使用 pickle 来保护一些字符串,并将昨天的字符串与今天的字符串进行比较。

filename = filename + '_yesterday.txt'
with open(filename, 'w+') as myfile:
     # if empty write something
     if os.path.getsize(myfile) == 0:
         myfile.write('write something')
     old_strings = pickle.load(myfile)
     all_strings = '....'

with open(filename, 'w') as myfile:
     pickle.dump(all_strings, myfile)

第一个问题:为什么我不能对文件使用 var-name 我总是遇到这个异常。

 with open(filename, 'w+') as myfile:
IOError: [Errno 2] No such file or directory:

第二个问题: 如果我将它与现有文件一起使用,则会出现此异常:

          if os.path.getsize(myfile) == 0:
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py", line 49, in getsize
    return os.stat(filename).st_size
TypeError: coercing to Unicode: need string or buffer, file found

最佳答案

您需要使用模式'wb+'打开文件

关于Python - 使用pickle时发生类型错误 - 如何正确使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31915747/

相关文章:

git - 如何让 VSCode 强制重新加载已更改的文件?

python - 害怕 "not the same object error" pickle 一个 queryset.query 对象

python - 如何将 Django 开发者服务器连接到 MySQL 数据库?

python - 区域设置和温度/长度转换

c++ - 我如何读取文件的最后一行

c++ - 使用标准 C++ 复制大型二进制文件

python - Pickle: AttributeError: 'module' 对象没有属性

python - pickle python 类实例

python - Gensim Doc2Vec 异常 AttributeError : 'str' object has no attribute 'decode'

python - 在 python,openCV 中使用网络摄像头的问题