python writes the csv scrambled code problem solution

  • 2020-05-12 02:52:54
  • OfStack

Demand background

Recently, I have developed a set of daily mail program for the company. The first email is the form, the picture and then the attachment. Attachment 1 is the default wrote txt file, but PM hope E-mail attachments can directly use Excel this software to open, the most began to want to save for Excel, but 1 think Excel file will be many times more volume, also use Excel open csv file by default, but also a text file, small volume, is convenient, and eventually decided to use csv module to save the file.

Python writes csv files

Python provides a built-in module for reading and writing csv files. I only need to write here, but I will not introduce it here. It is not difficult, mainly to solve the problem of scrambled codes.


def save2csv(file_name=None, header=None, data=None):
"""
 Save as CSV Format file , convenient Excel Directly open 
:param file_name:  Saved file name 
:param header:  header , every 1 The name of the column 
:param data:  Concrete fill data 
:return:
"""
if file_name is None or isinstance(file_name, basestring) is False:
raise Exception(' save CSV The file name cannot be empty , And must be of type string ')
if file_name.endswith('.csv') is False:
file_name += '.csv'
file_obj = open(file_name, 'wb')
file_obj.write(codecs.BOM_UTF8) #  To prevent the code 
writer = csv.writer(file_obj)
if data is None or isinstance(data, (tuple, list)) is False:
raise Exception(' save CSV The file failed , The data is null or not a data type ')
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 3 sentences that are meant to prevent confusion


file_obj = open(file_name, 'wb')
file_obj.write(codecs.BOM_UTF8) #  To prevent the code 
writer = csv.writer(file_obj)

This is prevented by writing codecs.BOM_UTF8 in the header of the file, which is encoded in utf-8

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: