我正在编写一个函数,该函数读取文件中的数据并向后打印,然后打印其中的字符数。为此,我正在使用
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/