【问题标题】:Python - TypeError occured while using pickle - how to use it correctPython - 使用pickle时发生TypeError - 如何正确使用它
【发布时间】:2015-08-10 09:13:54
【问题描述】:

我想使用 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

【问题讨论】:

  • 你的缩进是否正确
  • @VigneshKalai 抱歉,现在它是正确的。
  • 你能打印文件名吗
  • python 2 还是 3?我认为您使用 unicode 文件名
  • @VigneshKalai 已经完成,很好。我将代码简化为: with open('test.txt', 'r') as myfile: old_str = pickle.load(myfile) - 它仍然无法解决我得到: File "/System/Library/Frameworks /Python.framework/Versions/2.7/lib/python2.7/pickle.py”,第 1378 行,在加载返回 Unpickler(file).load() 文件“/System/Library/Frameworks/Python.framework/Versions/2.7 /lib/python2.7/pickle.py”,第 858 行,在加载调度 [key](self) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py ",第 880 行,在 load_eof 中引发 EOFError EOFError

标签: python file pickle


【解决方案1】:

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

【讨论】:

  • 为什么是 wb+ ?我认识到,如果文件有 '(lp0 .' 作为字符串,它可以解决吗?为什么?
  • 但我仍然有 var 文件名而不是字符串的问题 - open(filename, 'rb+') as myfile: IOError: [Errno 2] No such file or directory:
  • 您使用 wb+ 是因为我假设您在分配 'w+' 模式时知道自己在做什么。我也知道您选择的模式下的泡菜是二进制文件。在大多数操作系统中,您需要将'b'添加到模式中才能写入不是ascii。
  • 要解决其他问题,请查看@hspandher 的回答
  • 但是为什么如果我的文件没有 '(lp0 .' 在里面呢?文件 "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2 .7/pickle.py”,第 1378 行,在加载返回 Unpickler(file).load() 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py”,第 858 行,在加载调度 [key](self) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py”中,第 880 行,在 load_eof 中引发 EOFError EOFError跨度>
【解决方案2】:

os.stat 需要文件路径作为参数而不是文件对象。这会在您执行if os.path.getsize(myfile) == 0 时导致错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多