Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python (结果,消耗)=自身缓冲区解码(数据,自身错误,最终)错误_Python_File_Buffer - Fatal编程技术网

Python (结果,消耗)=自身缓冲区解码(数据,自身错误,最终)错误

Python (结果,消耗)=自身缓冲区解码(数据,自身错误,最终)错误,python,file,buffer,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行的短文件(顾名思义,它一定是一首诗),但当我写整首诗时,它

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

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行数1(文件名、目录名):
path=os.path.join(目录名,文件名)
行数=0
对于打开的行(路径“rb”):
行数+=1
返回num_行

这似乎根本不是长度问题。该错误表示这是一个unicode错误,并告诉您有一个字节无法解码为utf-8。当你打开文件时,你说编码是utf-8,但这个错误表明它不是。你需要知道正确的编码。是的,我已经发现了错误,我不知道utf-8不能解码这些类型的字符(ñ,á,,),你知道哪种编码可以吗?utf-8可以解码这些字符,但前提是它们是用utf-8编码的。您需要知道输入的编码,它可以是许多不同的东西(其中许多可以以不兼容的方式编码这些字符)。也就是说,当事物不是utf-8(也不是ascii)时,它们通常是拉丁语,而TF-8可以很好地处理字符。然而,utf-8是一种编码。这意味着,当您说
encoding=“utf-8”
Python期望这是文件的编码格式。但是,您的文件是以另一种格式编码的。也许是
拉丁语-1
?因此,为了让Python正确地阅读它,您必须说明这就是编码。@Eran和JohanL,它与latin1配合得很好,谢谢,还有一个问题,我如何知道输入的编码?