【问题标题】:Python Overwrite Dictionary to Text File doesn't work... why?Python覆盖字典到文本文件不起作用......为什么?
【发布时间】:2015-02-13 21:06:14
【问题描述】:


我之前一直在为一个测验程序编写代码,其中包含一个存储所有参与者结果的文本文件。将文本文件转换为字典的代码和文本文件本身如下所示:

代码:

import collections
from collections import defaultdict
scores_guessed = collections.defaultdict(lambda: collections.deque(maxlen=4))
with open('GuessScores.txt') as f:
    for line in f:
        name,val = line.split(":")
        scores_guessed[name].appendleft(int(val))

for k in sorted(scores_guessed):
    print("\n"+k," ".join(map(str,scores_guessed[k])))

writer = open('GuessScores.txt', 'wb')

for key, value in scores_guessed.items():       
    output = "%s:%s\n" % (key,value)
    writer.write(output)

文本文件如下所示:

Jack:10
Dave:20
Adam:30
Jack:40
Adam:50
Dave:60
Jack:70
Dave:80
Jack:90
Jack:100
Dave:110
Dave:120
Adam:130
Adam:140
Adam:150

现在,当我运行程序代码时,字典显示如下:

Adam 150 140 130 50

Dave 120 110 80 60

Jack 100 90 70 40

现在,这会将字典按最高分的顺序排列,然后是前 4 分!

我希望 python IDLE 将 GuessScores.txt 覆盖为:

Adam:150
Adam:140
Adam:130
Adam:50
Dave:120
Dave:110
Dave:80
Dave:60
Jack:100
Jack:90
Jack:70
Jack:40

但是当我运行代码时,出现了这个错误:

Traceback (most recent call last):
  File "/Users/Ahmad/Desktop/Test Files SO copy/readFile_prompt.py", line 16, in <module>
    writer.write(output)
TypeError: 'str' does not support the buffer interface

GuessScores.txt 文件是空的,因为它无法写入该文件,因为存在上述错误。

为什么会这样?解决方法是什么?我以前问过这个,但有很多问题。我在 Mac 10.8 Mavericks iMac 上运行 Python 3.3.2,如果有帮助的话。

谢谢, 德尔伯特。

【问题讨论】:

标签: python dictionary interface buffer python-idle


【解决方案1】:

第一个问题是您试图将文本写入以二进制模式打开的文件。在 3.x 中,这将不再起作用。 “文本”与“二进制”过去的意义很小(仅影响行尾翻译,因此在某些系统上根本没有区别)。现在它的意思就像它听起来的样子:以文本模式打开的文件是将其内容视为具有某种特定编码的文本的文件,以二进制模式打开的文件是将其内容视为字节序列的文件.

因此,您需要open('GuessScores.txt', 'w'),而不是open('GuessScores.txt', 'wb')

也就是说,您确实应该使用with 块来管理文件,并且您将不得不编写代码,以您想要的方式实际格式化字典内容。我假设您打算按排序的名称顺序输出,并且您需要遍历每个双端队列并为每个项目写一行。比如:

with open('GuessScores.txt', 'w') as f:
    for name, scores in sorted(scores_guessed.items()):
        for score in scores:
            f.write("{}:{}\n".format(name, score))

(还要注意新式格式。)

如有必要,您可以使用encoding 关键字参数在open 调用中显式指定文件的编码。 (如果您不知道我所说的“编码”是什么意思,那么您必须学习。我是认真的。放下所有东西并查一下。)

【讨论】:

  • 该块的最后一行不应该是scores_guessed.write("{}:{}\n".format(name, score))
  • 您正在尝试写入文件。该文件在第 1 行以f 打开。您必须写入文件,而不是猜测的分数字典。
【解决方案2】:

书写问题与open 函数中的b 有关。您已以二进制模式打开它,因此只能写入字节。您可以删除b 或在output 上调用bytes 以赋予它正确的类型。无论如何,你有一个逻辑错误。当我在 Python 2.7 上运行它时,GuessedScores.txt 的输出是这样的:

戴夫:deque([120,110,80,60],maxlen=4)
杰克:deque([100, 90, 70, 40], maxlen=4)
Adam:deque([150, 140, 130, 50], maxlen=4)

因此,您的值是整个双端队列,而不是单个分数。您必须格式化它们,类似于您在打印语句中所做的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2019-12-07
    • 1970-01-01
    相关资源
    最近更新 更多