Python 尝试编写 cPickle 对象但收到“写入”属性类型错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29127593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:07:14  来源:igfitidea点击:

Trying to write a cPickle object but get a 'write' attribute type error

pythonpickle

提问by Johnliquid

When trying to apply some code I found on the internet in iPython, it's coming up with an error:

当我尝试在 iPython 中应用我在互联网上找到的一些代码时,它出现了一个错误:

TypeError                                 Traceback (most recent call last)
    <ipython-input-4-36ec95de9a5d> in <module>()
     13     all[i] = r.json()
     14 
---> 15 cPickle.dump(all, outfile)

TypeError: argument must have 'write' attribute

Here's what I have done in order:

这是我按顺序完成的操作:

outfile = "C:\John\Footy Bants\R COMPLAEX MATHS"

Then, I pasted in the following code:

然后,我粘贴了以下代码:

import requests, cPickle, shutil, time

all = {}
errorout = open("errors.log", "w")

for i in range(600):
    playerurl = "http://fantasy.premierleague.com/web/api/elements/%s/"
    r = requests.get(playerurl % i)

    # skip non-existent players
    if r.status_code != 200: continue

    all[i] = r.json()

cPickle.dump(all, outfile)

Here's the original article to give you an idea of what I'm trying to achieve:

这是原始文章,让您了解我正在努力实现的目标:

http://billmill.org/fantasypl/

http://billmill.org/fantasypl/

回答by Martijn Pieters

The second argument to cPickle.dump()must be a file object. You passed in a string containing a filename instead.

的第二个参数cPickle.dump()必须是文件对象。您传入了一个包含文件名的字符串。

You need to use the open()function to open a file object for that filename, then pass the file object to cPickle:

您需要使用该open()函数为该文件名打开一个文件对象,然后将该文件对象传递给cPickle

with open(outfile, 'wb') as pickle_file:
    cPickle.dump(all, pickle_file)

See the Reading and Writing Filessectionof the Python tutorial, including why using withwhen opening a file is a good idea (it'll be closed for you automatically).

请参阅Python 教程的读取和写入文件部分,包括为什么with在打开文件时使用是个好主意(它会自动为您关闭)。