#-*-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)