【问题标题】:TypeError '_io.TextIOWrapper' object does not support item assignmentTypeError '_io.TextIOWrapper' 对象不支持项目分配
【发布时间】:2016-07-31 14:58:18
【问题描述】:

我正在编写一个测验,学生完成测验后,在保存分数时,我试图确保将学生的最后三个分数保存到他们的名字中。如果他们之前没有完成过测验,则会在文本文件中为他们写一个新行。

filename = (str(class_number) + 'txt')
with open(filename, 'a') as f:
    f.write(str(name) + " : " + str(score) + '\n')
with open(filename) as f:
    lines = [line for line in f if line.strip()]
    lines.sort()

with open(filename) as f:
    f.seek(0)
    scores = f.readline()
    from collections import deque
    for line in scores:
        score= int(score)
        if name not in f:
            f[name] = deque(maxlen=3)
        temp_q = filename[name]
        temp_q.append(str(score))
        filename[name] = temp_q

    filehandle = open (filename, 'w')
    for key,values in filename.iteritems():
        filehandle.write(name + ',')
        filehandle.write (','.join(list(values)) + '\n')
    filehandle.close()

这是错误:

f[name] = deque(maxlen=3)

TypeError '_io.TextIOWrapper' object does not support item assignment 

【问题讨论】:

    标签: python random collections typeerror deque


    【解决方案1】:

    您正在尝试将项目分配给打开的文件对象f 这里:

    f[name] = deque(maxlen=3)
    

    我不清楚你想在这里实现什么,但文件对象不是映射(字典)。

    您必须先解析文件的内容到字典中,进行更改,然后写回结果:

    scores = {}
    with open(filename) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            name, _, score = line.partition(':')
            scores.setdefault(name.strip(), []).append(int(score))
    

    这构建了一个字典映射,从名称到分数的列表;因为您的文件中每个名称可以包含多个分数。

    【讨论】:

    • 感谢您的帮助,如果我实现您的 r 代码,我相信代码会运行,但我想要实现的是最后三个分数保存到学生姓名,因此如果学生输入一个已经在文本文件中的名称,那么它会简单地将它添加到最后一个分数,但是如果它到达一个文件中将有 4 个分数的地步,它将丢弃第一个分数,只保存最近的三个分数。跨度>
    • @user6173661:我熟悉此任务的 GSCE 要求,是的。但是,您需要自己解决这个问题;我帮你解决了这个具体问题,它是通往完整任务解决方案的一个路标。
    猜你喜欢
    • 2014-02-18
    • 2017-03-26
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 2013-08-16
    • 1970-01-01
    相关资源
    最近更新 更多