写入csv文件时删除\ xa0

时间:2018-07-03 15:44:53

标签: python

我有以下代码将列表项写为csv文件。但是在执行此操作时,我看到输出的csv文件中出现特殊字符Â。为了在本地进行测试,我定义了一个列表项,其中包含字符'\ xao'的列表,并测试了各种方法来删除该列表并替换为空格。但是,我仍然在csv输出中得到特殊字符。有人可以帮忙吗?

import csv
from flask import make_response
import StringIO

csv_list = [['hfhf\xa0 fsdg','dsf'],['fsdgs fsdfs','fsdfsd'],['dsf\xa0 sf','asfg']]    

def download_csv_summary(csv_list):

si = StringIO.StringIO()
cw = csv.writer(si)
filename = 'Test'
cw.writerows(csv_list)        
output = make_response(si.getvalue())
output.headers['Content-Disposition'] = \
    'attachment; filename={filename}.csv'.format(filename=filename)
output.headers['Content-Type'] = 'text/csv'
return output

1 个答案:

答案 0 :(得分:0)

writerows行需要更改以替换\xa0

import csv
from flask import make_response
import StringIO

csv_list = [
    ['hfhf\xa0 fsdg','dsf'],
    ['fsdgs fsdfs','fsdfsd'],
    ['dsf\xa0 sf','asfg']
]

def download_csv_summary(csv_list):
    si = StringIO.StringIO()
    cw = csv.writer(si)
    filename = 'Test'

    cw.writerows([[str(x).replace('\xa0', '') for x in l] for l in csv_list])

    output = make_response(si.getvalue())
    output.headers['Content-Disposition'] = \
        'attachment; filename={filename}.csv'.format(filename=filename)
    output.headers['Content-Type'] = 'text/csv'
    return output