Python f.readline 读取文件报错:'gbk' codec can't decode byte ...
Python f.readline 读取文件报错:'gbk' codec can't decode byte ...
在 Python 中使用 f.readline() 函数逐行读取文件时,你可能会遇到类似 "'gbk' codec can't decode byte 0x80 in position 3796: illegal multibyte sequence" 的错误。这是因为文件中包含了无法被 'gbk' 编码解析的非法多字节序列。
要解决这个问题,你需要使用正确的编码格式来读取文件。
1. 指定编码格式
在使用 f.readline() 读取文件时,可以通过 encoding 参数指定文件的编码格式。例如:
with open('file.txt', 'r', encoding='utf-8') as f:
line = f.readline()
while line:
# 处理每一行数据
print(line)
line = f.readline()
你需要将 'utf-8' 替换为文件的实际编码格式,例如 'gbk' 或其他编码格式。
2. 自动检测编码
如果你不确定文件的编码格式,可以使用 chardet 库来自动检测。
import chardet
with open('file.txt', 'rb') as f:
result = chardet.detect(f.read())
encoding = result['encoding']
with open('file.txt', 'r', encoding=encoding) as f:
line = f.readline()
while line:
# 处理每一行数据
print(line)
line = f.readline()
这段代码首先使用 chardet.detect() 函数检测文件的编码格式,然后将检测到的编码格式作为参数传递给 open() 函数。
通过以上方法,你可以使用正确的编码格式读取文件,并避免 "'gbk' codec can't decode byte ..." 错误。
原文地址: https://www.cveoy.top/t/topic/fRR 著作权归作者所有。请勿转载和采集!