1
ファイルがあり、utf8エンコーディングに変換したい場合。「UnicodeDecodeError: 'utf-8'コーデックでデコードできない」エラーが表示されるため、ファイルを読み取れません。
私が読みたい場合は、私はこのエラーが表示されます。
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 947: invalid continuation byte
私の目的は、それを読んで、その後、UTF8エンコーディング形式に変換することでしたが、それは読んで許可されていません。ここで
は私のコードです:
#convert all files into utf_8 format
import os
import io
path_directory="some path string"
directory = os.fsencode(path_directory)
for file in os.listdir(directory):
file_name=os.fsdecode(file)
file_path_source=path_directory+file_name
file_path_dest="some address to destination file"
with open(file_path_source,"r") as f1:
text=f1.read()
with io.open(file_path_dest,"w+",encoding='utf8') as f2:
f2.write(text)
file_path=""
file_name=""
text=None
とエラーは次のとおりです。
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-47-59e5e52ddd40> in <module>()
10 with open(file_path,"r") as f1:
11 print(type(f1))
---> 12 text=f1.read()
13 with io.open(file_path.replace("ref_sum","ref_sum_utf_8"),"w+",encoding='utf8') as f2:
14 f2.write(text)
/home/afsharizadeh/anaconda3/lib/python3.6/codecs.py in decode(self, input, final)
319 # decode input (taking the buffer into account)
320 data = self.buffer + input
--> 321 (result, consumed) = self._buffer_decode(data, self.errors, final)
322 # keep undecoded input until the next call
323 self.buffer = data[consumed:]
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 947: invalid continuation byte
私は私のファイルは、それらを読まずにUTF8に変換することができますか?
これはあまりにも多くのヒットを得るために検索が難しくなるほど頻繁にポップアップします。あなたはすでに* utf-8であるとPythonに伝えていますが、それは真実ではないので、それを解読することはできません。 –
ファイルにutfヘッダーが含まれていますか。ファイルの先頭に '# - * - coding:utf-8 - * - 'と書かれています。 – 0decimal0
@ 0decimal0いいえ、そうではありません。 – mahsa