Writing to CSV in Python - codingem.com
文章推薦指數: 80 %
The 4 Steps to Writing a CSV in Python · Open a CSV file in the write mode. This happens using the open() function. · Create a CSV writer object. To do this, ... SkiptocontentTowritetoCSVinPython,usePython’scsvmodule.Forexample,let’swritealistofstringsintoanewCSVfile:importcsv data=["This","is","a","Test"] withopen('example.csv','w')asfile: writer=csv.writer(file) writer.writerow(data)Asaresult,youseeafilecalledexample.csvinthecurrentfolder.Thiswasthequickanswer.ButthereisalotmoretocoverwhenitcomestowritingCSVfilesinPython.Let’sjumpintothedetailsandseesomeusefulexamples.Bytheway,ifyouareinterestedinbecomingadatascientist,checkouttheseawesomePythonDataSciencecourses!WritingtoCSVinPythoninDetailCSVorcomma-separatedvaluesisatextfile.Itconsistsofcomma-separateddata.CSVisausefuldataformatforapplicationstotransferdata.TheCSVisasimplelightweighttextfile.Thismakesitaperfectfitforsendingandreceivingdatainanefficientway.Forexample,youcanretrievedatafromadatabaseasaCSV.OryoucanaddanewentrytoadatabaseusingCSVformat.HereisanexampleofwhatCSVdatalookslike:However,inthisguide,I’musingMac’sbuilt-inCSVviewer.ThustheCSVdatalooksmorelikethis:Intheintroduction,yousawasimpleexampleofhowtowriteapieceofdataintoaCSVfile.Let’snowtakeadeeperlookathowtowriteCSVfileswithPython.The4StepstoWritingaCSVinPythonTowritetoaCSVfileinPython:OpenaCSVfileinthewritemode.Thishappensusingtheopen()function.Giveitthepathofthefileasthefirstargument.Specifythemodeasthesecondargument('r'forreadand'w'forwrite).CreateaCSVwriterobject.Todothis,createacsvmodule’swriter()object,andpasstheopenedfileasitsargument.WritedatatotheCSVfile.Usethewriterobject’swriterow()functiontowritedataintotheCSVfile.ClosetheCSVfileusingtheclose()methodofafile.Hereisanexamplethatillustratesthisprocess:importcsv #1. file=open('test.csv','w') #2. writer=csv.writer(file) #3. data=["This","is","a","Test"] writer.writerow(data) #4. file.close()Thispieceofcodecreatesafilecalledtest.csvintothecurrentfolder.Theopen()functionopensanewfileifthefilespecifieddoesnotexist.Ifitdoes,thentheexistingfileisopened.TheShorthandApproachTomakewritingtoCSVabitshorter,usethewithstatementtoopenthefile.Thiswayyoudon’tneedtoworryaboutclosingthefileyourself.Thewithtakescareofthatpartautomatically.Forinstance:importcsv #1.step withopen('example.csv','w')asfile: #2.step writer=csv.writer(file) #3.step data=["This","is","a","Test"] writer.writerow(data)ThiscreatesanewCSVfilecalledexample.csvinthecurrentfolderandwritesthelistofstringstoit.HowtoWriteNon-ASCIICharacterstoaCSVinPythonBydefault,youcannotwritenon-ASCIIcharacterstoaCSVfile.Tosupportwritingnon-ASCIIvaluestoaCSVfile,specifythecharacterencodingintheopen()callasthethirdargument.withopen('PATH_TO_FILE.csv','w',encoding="UTF8")Therestoftheprocessfollowsthestepsyoulearnedearlier.HowtoCreateaHeaderfortheCSVFileSofaryouhavecreatedCSVfilesthatlackthestructure.InPython,itispossibletowriteaheaderforanyCSVfileusingthesamewriterow()functionyouusetowriteanydatatotheCSV.Example.Let’screateanexampleCSVfilethatconsistsofstudentdata.Tostructurethedatanicely,createaheaderforthestudentsandinsertitatthebeginningoftheCSVfile.Afterthis,youcanfollowthesamestepsfromearliertowritethedataintoaCSVfile.Hereisthecode:importcsv #Definethestructureofthedata student_header=['name','age','major','minor'] #Definetheactualdata student_data=['Jack',23,'Physics','Chemistry'] #1.OpenanewCSVfile withopen('students.csv','w')asfile: #2.CreateaCSVwriter writer=csv.writer(file) #3.Writedatatothefile writer.writerow(student_header) writer.writerow(student_data)Thiscreatesstudents.csvfileintothefolderyouarecurrentlyworkingin.Thenewfilelookslikethis:HowtoWriteMultipleRowsintoaCSVFileinPythonInPython,youcanusetheCSVwriter’swriterows()functiontowritemultiplerowsintoaCSVfileonthesamego.Example.Let’ssayyouwanttowritemorethanonelineofdataintoyourCSVfile.Forinstance,youmayhavealistofstudentsinsteadofonlyhavingoneofthem.TowritemultiplelinesofdataintoaCSV,usethewriterows()method.Hereisanexample:importcsv student_header=['name','age','major','minor'] student_data=[ ['Jack',23,'Physics','Chemistry'], ['Sophie',22,'Physics','ComputerScience'], ['John',24,'Mathematics','Physics'], ['Jane',30,'Chemistry','Physics'] ] withopen('students.csv','w')asfile: writer=csv.writer(file) writer.writerow(student_header) #Usewriterows()notwriterow() writer.writerows(student_data)ThisresultsinanewCSVfilethatlookslikethis:HowtoWriteaDictionarytoaCSVFileinPythonTowriteadictionaryintoaCSVfileinPython,usetheDictWriterobjectbyfollowingthesethreesteps:Useacsvmodule’sDictWriterobjectandspecifythefieldnamesinit.Usethewriteheader()methodtocreatetheheaderintotheCSVfile.usethewriterows()methodtowritethedictionarydataintothefile.Example.Let’swriteadictionaryofstudentdataintoaCSV.importcsv student_header=['name','age','major','minor'] student_data=[ {'name':'Jack','age':23,'major':'Physics','minor':'Chemistry'}, {'name':'Sophie','age':22,'major':'Physics','minor':'ComputerScience'}, {'name':'John','age':24,'major':'Mathematics','minor':'Physics'}, {'name':'Jane','age':30,'major':'Chemistry','minor':'Physics'} ] withopen('students.csv','w')asfile: #CreateaCSVdictionarywriterandaddthestudentheaderasfieldnames writer=csv.DictWriter(file,fieldnames=student_header) #Usewriterows()notwriterow() writer.writeheader() writer.writerows(student_data)Nowtheresultisthesamestudents.csvfileasintheearlierexample:ConclusionCSVorcomma-separatedvaluesisacommonlyusedfileformat.Itconsistsofvaluesthatareusuallyseparatedbycommas.TowriteintoaCSVinPython,youneedtousethecsvmodulewiththesesteps:OpenaCSVfileinthewritemode.CreateaCSVwriterobject.WritedatatotheCSVfile.ClosetheCSVfile.Hereisapracticalexample.importcsv data=["This","is","a","Test"] withopen('example.csv','w')asfile: writer=csv.writer(file) writer.writerow(data)Thanksforreading.Ihopeyoufindituseful.Happycoding!BestPythonCoursesforDataScienceFurtherReading50PythonInterviewQuestionsandAnswers50+BuzzwordsofWebDevelopmentPostnavigation←PreviousPostNextPost→LeaveaCommentYouremailaddresswillnotbepublished.Requiredfieldsaremarked*Typehere..Name*E-mail*Website reportthisadSearchfor: Search reportthisadAbouttheAuthorHi,I'mArtturiJalli!I'maTechenthusiastfromFinland.ImakeCoding&Techeasyandfunwithwell-thoughthow-toguidesandreviews.I'vealreadyhelped2M+visitorsreachtheirgoals!Contact13BestAIArtGeneratorsof2022(Free&Paid)AIistakingover.WiththelatestadvancementsinAIartgeneration,youcancreatephotorealisticimagesoutofthinair.Thebestpartisyoudon’t...ContinueReadingHowtoMakeanApp—AComplete10-StepGuide[in2022]Areyoulookingtocreatethenextbest-sellerapp?Orareyoucuriousabouthowtocreateasuccessfulmobileapp?Thisisastep-by-stepguideon...ContinueReading9BestGraphicDesignCourses+Certification[in2022]Doyouwanttobecomeaversatileandskilledgraphicdesigner?Thisisacomprehensivearticleonthebestgraphicdesigncertificationcourses.Thesecoursesprepareyou...ContinueReading8BestPythonCourseswithCertifications[in2022]AreyoulookingtobecomeaprofessionalPythondeveloper?Orareyouinterestedinprogrammingbutdon’tknowwheretostart?Pythonisabeginner-friendlyandversatile...ContinueReading8BestSwift&iOSAppDevelopmentCourses[in2022]AreyoulookingtobecomeaniOSdeveloper?Doyouwanttocreateappswithanoutstandingdesign?Doyouwanttolearntocode?IOSApp...ContinueReadingHowtoStartaProgrammingBlog:ABeginner’sGuide[2022]Startingaprogrammingblogisagreatwaytoshareyourexpertiseandgetyourvoiceheard.Italsooffersyouachancetobuildanice...ContinueReadingRecentPosts13BestAIArtGeneratorsof2022(Free&Paid)AIGlossary:25+TermsforBeginners(in2022)9BestAIColorizersof2022—ColorizeBlack&WhiteImagesBestWebDesignSoftwareof2022(Ranked&Reviewed)7BestAIStoryGeneratorsof2022(Fiction,Novels,ShortStories)CategoriesArtificialIntelligenceCrypto&NFTDataScienceFavoritesiOSDevelopmentJavaScriptProgrammingProgrammingTipsPythonPythonforBeginnersSoftwareSwiftSwiftforBeginnersTechnologyWebdevelopmentreportthisadreportthisadx
延伸文章資訊
- 1Writing CSV files in Python - GeeksforGeeks
csv.writer class is used to insert data to the CSV file. This class returns a writer object which...
- 2csv — CSV File Reading and Writing — Python 3.10.7 ...
The csv module implements classes to read and write tabular data in CSV format. ... The Python En...
- 3How to Write to CSV Files in Python
Steps for writing a CSV file · First, open the CSV file for writing ( w mode) by using the open()...
- 4Python CSV: Read and Write CSV files - Programiz
To write to a CSV file in Python, we can use the csv.writer() function. The csv.writer() function...
- 5[Day 04] CSV 讀寫操作 - iT 邦幫忙
The csv module 's reader and writer objects read and write sequences. ... 參考來源: 13.1. csv — CSV F...