Write to CSV file (write by line)

Source: Internet
Author: User

#-*-coding:utf-8-*-#python#Xiaodeng#Write to CSV file (write by line)ImportCSV#CSV file is a commonly used text format for storing tabular data, and many programs will encounter CSV format files when processing data#Write to CSV file (write by line)defgetsortedvalues (Row): Sortedvalues=[]#Initialize to empty listkeys=Row.keys () keys.sort ( ) forKeyinchkeys:sortedValues.append (Row[key])returnsortedvaluesrows= [{'Column1':'Xiaodeng','Column2':'1','Column3':'2'},        {'Column1':'Fengmei','Column2':'3','Column3':'4'},        {'Column1':'Xiaochen','Column2':'5','Column3':'6'},        {'Column1':'Xiaodong','Column2':'1','Column3':'2'},        {'Column1':'Xiaowang','Column2':'1','Column3':'2'}]names={'Column1':'name','Column2':'Section 2','Column3':'Section 3'}#open a file in a written wayFileobj=open ('Test.csv','WB')#attention is WB .Fileobj.write ('\XEF\XBB\XBF')#This statement solves the Chinese garbled problem#can be understood as initializationwriter = Csv.writer (fileobj)#Csv.writer (Fileobj) Return writer object writer#Write header information firstSortedvalues =getsortedvalues (names)#The Writerow () method is written one line at a#the Writerows method is to write multiple lines at onceWriter.writerow (sortedvalues)#write data row by line forRowinchrows:sortedvalues=getsortedvalues (Row)Printsortedvalues Writer.writerow (sortedvalues)

Write to CSV file (write by line)

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.