python - (result, consumed) = self._buffer_decode(data, self.errors, final) 错误

标签 python file buffer

我正在编写一个函数,该函数读取文件中的数据并向后打印,然后打印其中的字符数。为此,我正在使用

file=open("poem.txt", mode="r", encoding="utf-8");
x=file.read();
counter=len(x); #so here I could print counter to know the length of the file

然后我就在计数器和递减计数器的位置打印变量x。 这适用于 2 到 5 行的短文件,(顾名思义,它必须是一首诗),但是当我写整首诗时,它给了我这个错误

(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 43: invalid continuation byte

我很确定这是因为文件的长度,比如变量 x 不能承受那么多的数据,我只是想确保它是这样的。 提前致谢!

最佳答案

对我有用的解决方案是将文件模式从读取 (r) 更改为读取字节 (rb)。

def row_count1(filename, directory_name):

    path = os.path.join(directory_name,filename)

    num_rows = 0

    for row in open(path,"rb"):
        num_rows += 1

    return num_rows

关于python - (result, consumed) = self._buffer_decode(data, self.errors, final) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50266716/

相关文章:

python - 在列 * 和 * 索引上使用 groupby 和聚合与 Pandas 数据框

python - 使用 __name__ 作为属性

python - 值错误: I/O operation on closed file (File shouldn't be closed)

vim - 在 Vim 上的新选项卡上打开缓冲区

c - 与 Pthread 共享有界缓冲区和互斥锁忙等待

python - 长度为 k 的非重叠子串的随机采样

python - 如何使用 iloc[] 选择 pandas 数据框的倒数第二行?

php - 在 PHP 中按文件名对文件进行排序 - 2011 年 3 月、2011 年 4 月、2011 年 5 月等

c - 如何在 C 中创建和打开一个文件并使其对整个程序可用?

linux - 如何在连续的字符流中进行 grep 或 sed?