UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘\xa0‘ in position 2: illegal multibyte seque

python将列表各元素写入txt文件,一个元素占一行:

# df3是一个dataframe
file_handle = open(r"E:\work_notebook\区域+人群-商品类目相关性分析\df3_cols.txt",mode='w')
for col in df3.columns:
    col1 = col + ' ' + 'float,'
    file_handle.write(col1 + '\n')
file_handle.close()   # 必须要加close,不然数据无法存入进去

报错:

UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 2: illegal multibyte sequence

原因:

在windows下面,新文件的默认编码是gbk,这样的话,python解释器会用gbk编码去解析我们的网络数据流txt,然而txt此时已经是decode过的unicode编码,这样的话就会导致解析不了,出现上述问题。 解决的办法就是,改变目标文件的编码:

file_handle = open(r"E:\work_notebook\区域+人群-商品类目相关性分析\df3_cols.txt",mode='w', encoding='utf-8')

至此,问题得到解决!

你可能感兴趣的:(list,txt,python)