簡體   English   中英

UnicodeDecodeError:“charmap”編解碼器無法解碼位置 2433 中的字節 0x9d:字符映射到<undefined>

[英]UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2433: character maps to <undefined>

我正在使用以下代碼將文本文件寫入變量

from pathlib import Path
paragraph = Path('myfile.txt', encoding='utf-8').read_text()

我收到以下錯誤

Traceback (most recent call last):
  File "Z:\python\projects\vb\test.py", line 4, in <module>
    paragraph = Path('myfile.txt', encoding='utf-8').read_text()
  File "C:\Users\zagg\AppData\Local\Programs\Python\Python310\lib\pathlib.py", line 1133, in read_text
    return f.read()
  File "C:\Users\zagg\AppData\Local\Programs\Python\Python310\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2470: character maps to <undefined>

我看到有相同錯誤的類似帖子,但沒有一個答案對我有用。 有什么建議么?

只需在.read_text()中添加encoding='utf-8'

paragraph = Path('myfile.txt').read_text(encoding='utf-8')

有趣的是, Path沒有定義__init__並且它的__new__優雅地忽略了傳遞給它的任何**kwargs 所以Path('myfile.txt', encoding='utf-8') encoding='utf-8'沒有任何作用。

另一方面, read_text確實接受encoding參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM