Requirements background
Recently developed a set of mail daily program for the company, Mail is usually a form, pictures, then the attachment. Attachments are usually written to the txt file, but PM hope that the attachment in the message can be opened directly with Excel, the first want to save as Excel, but a think of Excel file volume will be many times, CSV file by default is also open with Excel, but is still a text file, Small size, easy to save, and finally decided to use the CSV module to save the file.
Python writes CSV file
Python provides a built-in module read and write CSV file, here I only used to write, read here do not introduce, it is not difficult, mainly to solve garbled problem.
def save2csv (File_name=none, Header=none, Data=none): "" "Save the file in CSV format for Excel to open directly: param file_name: Saved file name: param header: Table header, name of each column: param data: Fill in the details: return: "" If file_name is None or isinstance (file_name, basestring) is False:raise Exception (' Save CSV file name cannot be empty and must be string type ') if File_name.endswith ('. csv ') is false:file_name + = '. csv ' file_obj = open (file_name, ' WB ') File_obj.write (codecs. BOM_UTF8) # prevents garbled writer = Csv.writer (file_obj) if data is None or isinstance (data, (tuple, list)) is False:raise Exception (' Failed to save CSV file, data is empty or not data type ') if header is not None and Isinstance (header, (tuple, list)) is True:writer.writerow (header) for RO W in Data:writer.writerow (row)
Note: There are three words to prevent garbled
File_obj = open (file_name, ' WB ') File_obj.write (codecs. BOM_UTF8) # prevent garbled writer = Csv.writer (file_obj)
Write codecs at the head of the file. Bom_utf8 can prevent garbled, files are utf-8 encoded format
Thank you for reading, hope to help everyone, thank you for the support of this site!