How to Write to CSV Files in Python

文章推薦指數: 80 %
投票人數:10人

Steps for writing a CSV file · First, open the CSV file for writing ( w mode) by using the open() function. · Second, create a CSV writer object by calling the ... SkiptocontentHome»PythonBasics»PythonWriteCSVFileSummary:inthistutorial,you’lllearnhowtowritedataintoaCSVfileusingthebuilt-incsvmodule.StepsforwritingaCSVfileTowritedataintoaCSVfile,youfollowthesesteps:First,opentheCSVfileforwriting(wmode)byusingtheopen()function.Second,createaCSVwriterobjectbycallingthewriter()functionofthecsvmodule.Third,writedatatoCSVfilebycallingthewriterow()orwriterows()methodoftheCSVwriterobject.Finally,closethefileonceyoucompletewritingdatatoit.Thefollowingcodeillustratestheabovesteps:importcsv #openthefileinthewritemode f=open('path/to/csv_file','w') #createthecsvwriter writer=csv.writer(f) #writearowtothecsvfile writer.writerow(row) #closethefile f.close() Codelanguage:Python(python)It’llbeshorterifyouusethewithstatementsothatyoudon’tneedtocalltheclose()methodtoexplicitlyclosethefile:importcsv #openthefileinthewritemode withopen('path/to/csv_file','w')asf: #createthecsvwriter writer=csv.writer(f) #writearowtothecsvfile writer.writerow(row) Codelanguage:PHP(php)Ifyou’redealingwithnon-ASCIIcharacters,youneedtospecifythecharacterencodingintheopen()function.ThefollowingillustrateshowtowriteUTF-8characterstoaCSVfile:importcsv #openthefileinthewritemode withopen('path/to/csv_file','w',encoding='UTF8')asf: #createthecsvwriter writer=csv.writer(f) #writearowtothecsvfile writer.writerow(row) Codelanguage:PHP(php)WritingtoCSVfilesexampleThefollowingexampleshowshowtowritedatatotheCSVfile:importcsv header=['name','area','country_code2','country_code3'] data=['Afghanistan',652090,'AF','AFG'] withopen('countries.csv','w',encoding='UTF8')asf: writer=csv.writer(f) #writetheheader writer.writerow(header) #writethedata writer.writerow(data) Codelanguage:PHP(php)Ifyouopenthecountries.csv,you’llseeoneissuethatthefilecontentshaveanadditionalblanklinebetweentwosubsequentrows:Toremovetheblankline,youpassthekeywordargumentnewline=''totheopen()functionasfollows:importcsv header=['name','area','country_code2','country_code3'] data=['Afghanistan',652090,'AF','AFG'] withopen('countries.csv','w',encoding='UTF8',newline='')asf: writer=csv.writer(f) #writetheheader writer.writerow(header) #writethedata writer.writerow(data)Codelanguage:PHP(php)Output:WritingmultiplerowstoCSVfilesTowritemultiplerowstoaCSVfileatonce,youusethewriterows()methodoftheCSVwriterobject.Thefollowingusesthewriterows()methodtowritemultiplerowsintothecountries.csvfile:importcsv header=['name','area','country_code2','country_code3'] data=[ ['Albania',28748,'AL','ALB'], ['Algeria',2381741,'DZ','DZA'], ['AmericanSamoa',199,'AS','ASM'], ['Andorra',468,'AD','AND'], ['Angola',1246700,'AO','AGO'] ] withopen('countries.csv','w',encoding='UTF8',newline='')asf: writer=csv.writer(f) #writetheheader writer.writerow(header) #writemultiplerows writer.writerows(data) Codelanguage:PHP(php)WritingtoCSVfilesusingtheDictWriterclassIfeachrowoftheCSVfileisadictionary,youcanusetheDictWriterclassofthecsvmoduletowritethedictionarytotheCSVfile.TheexampleillustrateshowtousetheDictWriterclasstowritedatatoaCSVfile:importcsv #csvheader fieldnames=['name','area','country_code2','country_code3'] #csvdata rows=[ {'name':'Albania', 'area':28748, 'country_code2':'AL', 'country_code3':'ALB'}, {'name':'Algeria', 'area':2381741, 'country_code2':'DZ', 'country_code3':'DZA'}, {'name':'AmericanSamoa', 'area':199, 'country_code2':'AS', 'country_code3':'ASM'} ] withopen('countries.csv','w',encoding='UTF8',newline='')asf: writer=csv.DictWriter(f,fieldnames=fieldnames) writer.writeheader() writer.writerows(rows) Codelanguage:PHP(php)Howitworks.First,definevariablesthatholdthefieldnamesanddatarowsoftheCSVfile.Next,opentheCSVfileforwritingbycallingtheopen()function.Then,createanewinstanceoftheDictWriterclassbypassingthefileobject(f)andfieldnamesargumenttoit.Afterthat,writetheheaderfortheCSVfilebycallingthewriteheader()method.Finally,writedatarowstotheCSVfileusingthewriterows()method.SummaryUsetheCSVWriterortheDictWriterclasstowritedatatoaCSVfile.PreviouslyPythonReadCSVFileUpNextPythonDeleteFileSearchfor:GettingStartedPythonFundamentalsControlFlowFunctionsPythonListPythonDictionaryPythonSetExceptionHandlingPythonLoopwithElseClauseMoreonFunctionsModulesFileI/ODirectoryManagingThird-partyPackages



請為這篇文章評分?