我试图让一个Python 3程序对一个充满信息的文本文件做一些操作。然而,当我试图读取文件时,我得到以下错误:

Traceback (most recent call last):  
   File "SCRIPT LOCATION", line NUMBER, in <module>  
     text = file.read()
   File "C:\Python31\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 0x90 in position 2907500: character maps to `<undefined>`  

当前回答

或者,如果你不需要解码文件,比如将文件上传到网站,可以使用:

open(filename, 'rb')

r =读数,b =二进制

其他回答

如果file = open(filename, encoding="utf-8")不起作用,请尝试 File = open(filename, errors="ignore"),如果你想删除不需要的字符。(文档)

或者,如果你不需要解码文件,比如将文件上传到网站,可以使用:

open(filename, 'rb')

r =读数,b =二进制

def read_files(file_path):

    with open(file_path, encoding='utf8') as f:
        text = f.read()
        return text

或(和)

def read_files(text, file_path):

    with open(file_path, 'rb') as f:
        f.write(text.encode('utf8', 'ignore'))

不要再浪费你的时间了,只要在读写代码中添加以下encoding="cp437"和errors='ignore'即可:

open('filename.csv', encoding="cp437", errors='ignore')
open(file_name, 'w', newline='', encoding="cp437", errors='ignore')

祝成功

对我来说,用utf16编码是有效的

file = open('filename.csv', encoding="utf16")