【问题标题】:Trying to write a cPickle object but get a 'write' attribute type error试图写一个 cPickle 对象但得到一个“写”属性类型错误
【发布时间】:2015-03-18 16:33:01
【问题描述】:

当我尝试在 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

这是我按顺序完成的:

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

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

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)

这是原始文章,可让您了解我想要实现的目标:

http://billmill.org/fantasypl/

【问题讨论】:

    标签: python pickle


    【解决方案1】:

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

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

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

    请参阅 Python 教程的 Reading and Writing Files section,包括为什么在打开文件时使用 with 是个好主意(它会自动为您关闭)。

    【讨论】:

    • 感谢 Martijn,虽然现在有文件,但我正在尝试将一些数据下载到 outfile 中,或者至少我认为我正在尝试这样做!这就是我想要复制的东西:billmill.org/fantasypl
    • @Johnliquid:我不可能看到你在这里缺少缩进的地方; with 语句下的块必须像 ifwhilefor 语句一样缩进。
    • 文件 "",第 7 行 playerurl = "fantasy.premierleague.com/web/api/elements/%s" ^ IndentationError: 需要缩进块
    • 向上箭头在 playerurl 下方
    • @Johnliquid:那么,您是否像在博客文章中那样缩进该行? Python 需要使用前导空格来表示块。也许您需要从 Python 教程开始?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 2021-10-23
    • 1970-01-01
    • 2019-07-24
    相关资源
    最近更新 更多