我怎样才能解决这个问题;ValueError:can';t没有无缓冲文本I/O“;在python 3中?

我怎样才能解决这个问题;ValueError:can';t没有无缓冲文本I/O“;在python 3中?,python,python-3.x,Python,Python 3.x,这是MIT python项目的一个问题,但它基本上是为python 2.x用户编写的,所以有没有办法修复以下代码以在最新的python 3中运行 当前代码引发“ValueError:不能有无缓冲文本I/O” 从打开的文档字符串: 。。。缓冲是用于设置缓冲策略的可选整数。 传递0以关闭缓冲(仅在二进制模式下允许) 因此更改infle=open(单词列表文件名'r',0) 到 infle=open(字列表文件名'r'),或 infle=open(WORDLIST_FILENAME'rb',0)如果您

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

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


打开
的文档字符串:

。。。缓冲是用于设置缓冲策略的可选整数。 传递0以关闭缓冲(仅在二进制模式下允许)

因此更改
infle=open(单词列表文件名'r',0)

infle=open(字列表文件名'r')
,或


infle=open(WORDLIST_FILENAME'rb',0)
如果您真的需要它(我对此表示怀疑)。

我可以通过使用以下代码来克服此错误:


这仅在打印与字节字符串一起使用时有效。看来我的答案更有效
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
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)