Home  >  Article  >  Backend Development  >  Solution to the problem of using python to generate csv garbled characters

Solution to the problem of using python to generate csv garbled characters

高洛峰
高洛峰Original
2017-03-16 16:11:401573browse

Requirement Background

Recently, a set of daily email programs have been developed for the company. The emails are generally forms, pictures, and then attachments. Attachments are generally written to txt files by default, but the PM hopes that the attachments in the email can be opened directly with software such as Excel. At first, he wanted to save it as Excel, but when he thought that the file size of Excel would be many times larger, the csv file defaulted It was also opened using Excel, but it was still a text file. It was small in size and easy to save, so I finally decided to use the csv module to save the file.

PythonWrite csv files

Python provides a built-in module to read and write csv files. Here I only use writing. I won’t introduce it here, and it is not difficult. , mainly to solve the problem of garbled characters.

def save2csv(file_name=None, header=None, data=None):
"""
保存成CSV格式文件,方便Excel直接打开
:param file_name: 保存的文件名
:param header: 表头,每一列的名字
:param data: 具体填充数据
:return:
"""
if file_name is None or isinstance(file_name, basestring) is False:
raise Exception('保存CSV文件名不能为空,并且必须为字符串类型')
if file_name.endswith('.csv') is False:
file_name += '.csv'
file_obj = open(file_name, 'wb')
file_obj.write(codecs.BOM_UTF8) # 防止乱码
writer = csv.writer(file_obj)
if data is None or isinstance(data, (tuple, list)) is False:
raise Exception('保存CSV文件失败,数据为空或者不是数据类型')
if header is not None and isinstance(header, (tuple, list)) is True:
writer.writerow(header)
for row in data:
writer.writerow(row)

Note: There are three sentences to prevent garbled characters

file_obj = open(file_name, 'wb')
file_obj.write(codecs.BOM_UTF8) # 防止乱码
writer = csv.writer(file_obj)

Writing codecs.BOM_UTF8 in the file header can prevent garbled characters. The files are all in utf-8 encoding format

The above is the detailed content of Solution to the problem of using python to generate csv garbled characters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn