文章内容
2021/1/4 16:44:52,作 者: 黄兵
ValueError: binary mode doesn't take an encoding argument
最近在使用python读取文件的时候出现如下错误:
ValueError: binary mode doesn't take an encoding argument
出现错误的原因:
在二进制模式下读取文件,不需要设置文件的编码方式,具体错误代码如下:
def read_processed_data(self):
# 读取已经处理的数据行
if os.path.exists(self._save_processed_data_txt_file):
with open(self._save_processed_data_txt_file, 'rb', encoding='utf-8') as txt_file:
processed_data = [line.rstrip() for line in txt_file]
return processed_data
同时如果是二进制写入的时候,设置编码方式也会出现错误,形如:
def write_processed_data(self, row_data):
# 写入已经处理的数据行
if os.path.exists(self._save_processed_data_txt_file):
with open(self._save_processed_data_txt_file, 'ab', encoding='utf-8') as txt_file:
txt_file.write(row_data)
解决方案:
删除编码方式:
def read_processed_data(self):
# 读取已经处理的数据行
if os.path.exists(self._save_processed_data_txt_file):
with open(self._save_processed_data_txt_file, 'rb') as txt_file:
processed_data = [line.rstrip() for line in txt_file]
return processed_data
黄兵个人博客原创。
转载请注明出处:黄兵个人博客 - ValueError: binary mode doesn't take an encoding argument
评论列表