Python write csv garbled problem resolution method

Source: Internet
Author: User
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!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.