如何修复python 3中的“ValueError:cannothaveunbufferedtexti/O”?

2024-04-26 11:34:31 发布

您现在位置:Python中文网/ 问答频道 /正文

这是麻省理工学院python项目的一个问题,但它基本上是为python 2.x用户编写的,所以有没有办法修复以下代码,以便在最新的python 3中运行?

当前代码正在引发“ValueError:不能有无缓冲文本I/O”

WORDLIST_FILENAME = "words.txt"

def load_words():

    print("Loading word list from file...")

    inFile = open(WORDLIST_FILENAME, 'r', 0)
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.append(line.strip().lower())
    print("  ", len(wordlist), "words loaded.")
    return wordlist

Tags: 项目代码用户文本txtlinefilenameinfile
2条回答

我可以使用this answer中的代码来克服此错误:

class Unbuffered(object):
    def __init__(self, stream):
        self.stream = stream

    def write(self, data):
        self.stream.write(data)
        self.stream.flush()

    def writelines(self, datas):
        self.stream.writelines(datas)
        self.stream.flush()

    def __getattr__(self, attr):
        return getattr(self.stream, attr)

import sys
sys.stdout = Unbuffered(sys.stdout)

来自open的docstring:

... buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode) ...

所以改变inFile = open(WORDLIST_FILENAME, 'r', 0)

inFile = open(WORDLIST_FILENAME, 'r'),或

如果你真的需要的话(我怀疑)。

相关问题 更多 >