尝试编写cPickle对象但得到'write'属性类型错误

Joh*_*uid 18 python pickle

当我尝试应用我在互联网上发现的一些代码时,它会出现错误:

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
Run Code Online (Sandbox Code Playgroud)

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

outfile = "C:\John\Footy Bants\R COMPLAEX MATHS"
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

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

http://billmill.org/fantasypl/

Mar*_*ers 32

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

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

with open(outfile, 'wb') as pickle_file:
    cPickle.dump(all, pickle_file)
Run Code Online (Sandbox Code Playgroud)

请参阅Python教程的阅读和编写文件部分,包括with打开文件时使用的原因是一个好主意(它将自动关闭).