This article introduces how to use python to generate csv garbled characters
Recently, we developed a Daily Mail program for our company. generally, emails are forms, images, and attachments. Attachments are generally written to txt files by default, but PM wants the attachments in the email to be opened directly using the Excel software and wants to be saved as Excel at first, however, the size of an Excel file is many times larger. csv files are opened in Excel by default, but they are still text files, which are small in size and easy to save, therefore, the csv module was used to save the file.
Write csv files in Python
Python provides a built-in module for reading and writing csv files. here I only use it for writing. I will not introduce it here, and it is not difficult, mainly to solve the garbled problem.
Def save2csv (file_name = None, header = None, data = None): "is saved as a CSV file. in Excel, you can directly open param file_name: saved File name: param header: header, the name of each column: param data: fill data: return: "if file_name is None or isinstance (file_name, basestring) is False: raise Exception ('save CSV file name cannot be blank 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 row in data: writer. writerow (row)
Note: There are three statements to prevent garbled characters.
File_obj = open (file_name, 'WB ') file_obj.write (codecs. BOM_UTF8) # prevent gibberish writer = csv. writer (file_obj)
Write codecs. BOM_UTF8 in the file header to prevent garbled characters. all files are in UTF-8 encoding format.
The above is a detailed description of the solution to csv garbled characters generated using python. For more information, see other related articles in the first PHP community!