Requirements background
Recently developed a set of mail daily program for the company, the mail is usually the form, picture, and then is the attachment. Attachments are generally written to TXT file by default, but PM hope that the attachment in the mail can be opened directly with Excel software, the first want to save as Excel, but one would like to Excel file volume will be many times, CSV file by default is also open with Excel, but it is still a text file, Small size, easy to save, and finally decided to use a CSV module to save the file.
Python write csv file
Python provides a built-in module to read and write CSV file, here I only use the write, read here do not introduce, also not difficult, is mainly to solve the garbled problem.
def save2csv (File_name=none, Header=none, Data=none): "" "
saved as a CSV format file to facilitate Excel to directly open
:p Aram file_name: The saved file name
:p Aram Header: header, name of each column
:p Aram data: "Return:" "'
if file_name is None or isinstance (file_name, basestring) is False:
raise Exception (' save CSV filename 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) # prevent garbled
writer = csv.writer (file_obj)
if data is None or isinstance (data, (tuple, list)) is false:
raise Exception (' Save CSV file failed, 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 words to prevent garbled
File_obj = open (file_name, ' WB ')
File_obj.write (codecs. BOM_UTF8) # prevent garbled
writer = Csv.writer (file_obj)
Writes codecs to the file header. Bom_utf8 will be able to prevent garbled, files are utf-8 encoded format
Thank you for reading, I hope to help you, thank you for your support for this site!