import codecs
class FileReader:
def __init__(self, file_path):
self.file_path = file_path
def read_file(self, encoding='utf-8'):
try:
with codecs.open(self.file_path, 'r', encoding=encoding) as f:
content = f.read()
return content
except UnicodeDecodeError:
print(f"无法使用 {encoding} 编码读取文件")
except FileNotFoundError:
print(f"文件 {self.file_path} 不存在")
使用到的标准库模块及其作用
codecs
:该模块提供了通用的编码和解码服务。在代码中使用 codecs.open
方法来打开文件,相比内置的 open
函数,codecs.open
对不同编码格式的支持更为灵活,能够处理多种编码格式的文件读取,例如 utf-8
、gbk
等。通过指定 encoding
参数,可以方便地按照指定编码格式读取文件内容。