Home  >  Article  >  Backend Development  >  How to solve the problem of garbled characters written to csv in python

How to solve the problem of garbled characters written to csv in python

WBOY
WBOYOriginal
2016-12-05 13:27:141227browse

Requirement background

Recently developed an email daily program for the company. The emails usually consist of tables, pictures, and 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.

Write csv file with Python

Python provides a built-in module to read and write csv files. Here I only use writing. I will not introduce it here. It is not difficult. The main purpose is 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 just to prevent garbled characters

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

Write codecs.BOM_UTF8 in the header of the file to prevent garbled characters. The files are all in UTF-8 encoding format

Thanks for reading, I hope it can help you, thank you for your support of this site!

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