解决方法:使用codecs,指定读取编码
文件内容:

原代码:
# -*- coding: utf-8 -*-
import datetime
import csv
import sys
import os
reload(sys)
sys.setdefaultencoding('utf8') # 设置编码
# 读取配置文件
def get_task_config(path):
task_config = [] # 配置列表 每一个元素为一行配置
f = open(path)
f_csv = list(csv.reader(f))
for row in f_csv[1:]: # 跳过表头
print(row)
task_config.append(row)
f.close()
print("读取配置文件成功")
return task_config
if __name__ == '__main__':
# 配置文件目录
config_path = '/home/deploy/tools/monitor/monitor_flow_config.csv'
task_config = get_task_config(config_path)
结果:

修改代码:
# 读取配置文件
def get_task_config(path):
task_config = [] # 配置列表 每一个元素为一行配置
# 读取配置文件
f = codecs.open(path, 'rb', 'gb2312')
f_csv = list(f)
for row in f_csv[1:]: # 跳过表头
print(row)
task_config.append(row)
f.close()
print("读取配置文件成功")
return task_config
结果:

该博客介绍了在Python中遇到的读取GBK编码文件的错误及解决方案。原始代码尝试通过`sys.setdefaultencoding()`设置编码,但此方法在标准Python中不推荐使用。修正后的代码使用`codecs`模块的`open()`函数,指定'rb'模式和'gb2312'编码来正确读取文件,从而避免了编码问题。
17万+

被折叠的 条评论
为什么被折叠?



