Python CSV: Read and Write CSV files - Programiz

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

To write to a CSV file in Python, we can use the csv.writer() function. The csv.writer() function returns a writer object that converts the user's data into a ... CourseIndex ExploreProgramiz Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLL PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear ExplorePythonExamples ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster BecomeaJavaMaster ViewallCourses Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython AllPythonTutorials ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall Python JavaScript C C++ Java Kotlin LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear AllPythonExamples LearnPythonInteractively PythonIntroduction GettingStarted KeywordsandIdentifier Statements&Comments PythonVariables PythonDataTypes PythonTypeConversion PythonI/OandImport PythonOperators PythonNamespace PythonFlowControl Pythonif...else PythonforLoop PythonwhileLoop Pythonbreakandcontinue PythonPass PythonFunctions PythonFunction FunctionArgument PythonRecursion AnonymousFunction Global,LocalandNonlocal PythonGlobalKeyword PythonModules PythonPackage PythonDatatypes PythonNumbers PythonList PythonTuple PythonString PythonSet PythonDictionary PythonFiles PythonFileOperation PythonDirectory PythonException ExceptionHandling User-definedException PythonObject&Class PythonOOP PythonClass PythonInheritance MultipleInheritance OperatorOverloading PythonAdvancedTopics PythonIterator PythonGenerator PythonClosure PythonDecorators PythonProperty PythonRegEx PythonExamples PythonDateandtime PythondatetimeModule Pythondatetime.strftime() Pythondatetime.strptime() Currentdate&time Getcurrenttime Timestamptodatetime PythontimeModule Pythontime.sleep() RelatedTopics WritingCSVfilesinPython WorkingwithCSVfilesinPython ReadingCSVfilesinPython Pythonopen() PythonFileI/O PythonJSON PythonCSV Inthistutorial,wewilllearnhowtoreadandwriteintoCSVfilesinPythonwiththehelpofexamples. ACSV(CommaSeparatedValues)formatisoneofthemostsimpleandcommonwaystostoretabulardata.TorepresentaCSVfile,itmustbesavedwiththe.csvfileextension. Let'stakeanexample: IfyouopentheaboveCSVfileusingatexteditorsuchassublimetext,youwillsee: SN,Name,City 1,Michael,NewJersey 2,Jack,California Asyoucansee,theelementsofaCSVfileareseparatedbycommas.Here,,isadelimiter. Youcanhaveanysinglecharacterasyourdelimiterasperyourneeds. Note:Thecsvmodulecanalsobeusedforotherfileextensions(like:.txt)aslongastheircontentsareinproperstructure. WorkingwithCSVfilesinPython Whilewecouldusethebuilt-inopen()functiontoworkwithCSVfilesinPython,thereisadedicatedcsvmodulethatmakesworkingwithCSVfilesmucheasier. Beforewecanusethemethodstothecsvmodule,weneedtoimportthemodulefirstusing: importcsv ReadingCSVfilesUsingcsv.reader() ToreadaCSVfileinPython,wecanusethecsv.reader()function.Supposewehaveacsvfilenamedpeople.csvinthecurrentdirectorywiththefollowingentries. Name Age Profession Jack 23 Doctor Miller 22 Engineer Let'sreadthisfileusingcsv.reader(): Example1:ReadCSVHavingCommaDelimiter importcsv withopen('people.csv','r')asfile: reader=csv.reader(file) forrowinreader: print(row) Output ['Name','Age','Profession'] ['Jack','23','Doctor'] ['Miller','22','Engineer'] Here,wehaveopenedthepeople.csvfileinreadingmodeusing: withopen('people.csv','r')asfile: ....... TolearnmoreaboutopeningfilesinPython,visit:PythonFileInput/Output Then,thecsv.reader()isusedtoreadthefile,whichreturnsaniterablereaderobject. Thereaderobjectistheniteratedusingaforlooptoprintthecontentsofeachrow. Intheaboveexample,weareusingthecsv.reader()functionindefaultmodeforCSVfileshavingcommadelimiter. However,thefunctionismuchmorecustomizable. SupposeourCSVfilewasusingtabasadelimiter.Toreadsuchfiles,wecanpassoptionalparameterstothecsv.reader()function.Let'stakeanexample. Example2:ReadCSVfileHavingTabDelimiter importcsv withopen('people.csv','r',)asfile: reader=csv.reader(file,delimiter='\t') forrowinreader: print(row) Noticetheoptionalparameterdelimiter='\t'intheaboveexample. Thecompletesyntaxofthecsv.reader()functionis: csv.reader(csvfile,dialect='excel',**optional_parameters) Asyoucanseefromthesyntax,wecanalsopassthedialectparametertothecsv.reader()function.Thedialectparameterallowsustomakethefunctionmoreflexible.Tolearnmore,visit:ReadingCSVfilesinPython. WritingCSVfilesUsingcsv.writer() TowritetoaCSVfileinPython,wecanusethecsv.writer()function. Thecsv.writer()functionreturnsawriterobjectthatconvertstheuser'sdataintoadelimitedstring.ThisstringcanlaterbeusedtowriteintoCSVfilesusingthewriterow()function.Let'stakeanexample. Example3:WritetoaCSVfile importcsv withopen('protagonist.csv','w',newline='')asfile: writer=csv.writer(file) writer.writerow(["SN","Movie","Protagonist"]) writer.writerow([1,"LordoftheRings","FrodoBaggins"]) writer.writerow([2,"HarryPotter","HarryPotter"]) Whenweruntheaboveprogram,aprotagonist.csvfileiscreatedwiththefollowingcontent: SN,Movie,Protagonist 1,LordoftheRings,FrodoBaggins 2,HarryPotter,HarryPotter Intheaboveprogram,wehaveopenedthefileinwritingmode. Then,wehavepassedeachrowasalist.TheselistsareconvertedtoadelimitedstringandwrittenintotheCSVfile. Example4:Writingmultiplerowswithwriterows() Ifweneedtowritethecontentsofthe2-dimensionallisttoaCSVfile,here'showwecandoit. importcsv csv_rowlist=[["SN","Movie","Protagonist"],[1,"LordoftheRings","FrodoBaggins"], [2,"HarryPotter","HarryPotter"]] withopen('protagonist.csv','w')asfile: writer=csv.writer(file) writer.writerows(csv_rowlist) TheoutputoftheprogramisthesameasinExample3. Here,our2-dimensionallistispassedtothewriter.writerows()methodtowritethecontentofthelisttotheCSVfile. Example5:WritingtoaCSVFilewithTabDelimiter importcsv withopen('protagonist.csv','w')asfile: writer=csv.writer(file,delimiter='\t') writer.writerow(["SN","Movie","Protagonist"]) writer.writerow([1,"LordoftheRings","FrodoBaggins"]) writer.writerow([2,"HarryPotter","HarryPotter"]) Noticetheoptionalparameterdelimiter='\t'inthecsv.writer()function. Thecompletesyntaxofthecsv.writer()functionis: csv.writer(csvfile,dialect='excel',**optional_parameters) Similartocsv.reader(),youcanalsopassdialectparameterthecsv.writer()functiontomakethefunctionmuchmorecustomizable.Tolearnmore,visit:WritingCSVfilesinPython Pythoncsv.DictReader()Class Theobjectsofacsv.DictReader()classcanbeusedtoreadaCSVfileasadictionary. Example6:Pythoncsv.DictReader() Supposewehavethesamefilepeople.csvasinExample1. Name Age Profession Jack 23 Doctor Miller 22 Engineer Let'sseehowcsv.DictReader()canbeused. importcsv withopen("people.csv",'r')asfile: csv_file=csv.DictReader(file) forrowincsv_file: print(dict(row)) Output {'Name':'Jack','Age':'23','Profession':'Doctor'} {'Name':'Miller','Age':'22','Profession':'Engineer'} Aswecansee,theentriesofthefirstrowarethedictionarykeys.And,theentriesintheotherrowsarethedictionaryvalues. Here,csv_fileisacsv.DictReader()object.Theobjectcanbeiteratedoverusingaforloop.Thecsv.DictReader()returnedanOrderedDicttypeforeachrow.That'swhyweuseddict()toconverteachrowtoadictionary. Noticethat,wehaveexplicitlyusedthedict()methodtocreatedictionariesinsidetheforloop. print(dict(row)) Note:StartingfromPython3.8,csv.DictReader()returnsadictionaryforeachrow,andwedonotneedtousedict()explicitly. Thefullsyntaxofthecsv.DictReader()classis: csv.DictReader(file,fieldnames=None,restkey=None,restval=None,dialect='excel',*args,**kwds) Tolearnmoreaboutitindetail,visit:Pythoncsv.DictReader()class Pythoncsv.DictWriter()Class Theobjectsofcsv.DictWriter()classcanbeusedtowritetoaCSVfilefromaPythondictionary. Theminimalsyntaxofthecsv.DictWriter()classis: csv.DictWriter(file,fieldnames) Here, file-CSVfilewherewewanttowriteto fieldnames-alistobjectwhichshouldcontainthecolumnheadersspecifyingtheorderinwhichdatashouldbewrittenintheCSVfile Example7:Pythoncsv.DictWriter() importcsv withopen('players.csv','w',newline='')asfile: fieldnames=['player_name','fide_rating'] writer=csv.DictWriter(file,fieldnames=fieldnames) writer.writeheader() writer.writerow({'player_name':'MagnusCarlsen','fide_rating':2870}) writer.writerow({'player_name':'FabianoCaruana','fide_rating':2822}) writer.writerow({'player_name':'DingLiren','fide_rating':2801}) Theprogramcreatesaplayers.csvfilewiththefollowingentries: player_name,fide_rating MagnusCarlsen,2870 FabianoCaruana,2822 DingLiren,2801 Thefullsyntaxofthecsv.DictWriter()classis: csv.DictWriter(f,fieldnames,restval='',extrasaction='raise',dialect='excel',*args,**kwds) Tolearnmoreaboutitindetail,visit:Pythoncsv.DictWriter()class UsingthePandaslibrarytoHandleCSVfiles PandasisapopulardatasciencelibraryinPythonfordatamanipulationandanalysis.Ifweareworkingwithhugechunksofdata,it'sbettertousepandastohandleCSVfilesforeaseandefficiency. Beforewecanusepandas,weneedtoinstallit.Tolearnmore,visit:HowtoinstallPandas? Onceweinstallit,wecanimportPandasas: importpandasaspd ToreadtheCSVfileusingpandas,wecanusetheread_csv()function. importpandasaspd pd.read_csv("people.csv") Here,theprogramreadspeople.csvfromthecurrentdirectory. TowritetoaCSVfile,weneedtocalltheto_csv()functionofaDataFrame. importpandasaspd #creatingadataframe df=pd.DataFrame([['Jack',24],['Rose',22]],columns=['Name','Age']) #writingdataframetoaCSVfile df.to_csv('person.csv') Here,wehavecreatedaDataFrameusingthepd.DataFrame()method.Then,theto_csv()functionforthisobjectiscalled,towriteintoperson.csv. Tolearnmore,visit: Pythonpandas.read_csv(officialsite) Pythonpandas.pandas.DataFrame.to_csv(officialsite) TableofContents WhatisaCSVFileFormat? ReadingCSVfilesUsingcsv.reader() WritingCSVfilesUsingcsv.writer() Pythoncsv.DictReader()Class Pythoncsv.DictWriter()Class UsingthePandaslibrarytoHandleCSVfiles Shareon: Didyoufindthisarticlehelpful? Sorryaboutthat. Howcanweimproveit? Feedback* Leavethisfieldblank RelatedTutorialsPythonTutorialWritingCSVfilesinPythonPythonTutorialWorkingwithCSVfilesinPythonPythonTutorialReadingCSVfilesinPythonPythonLibraryPythonopen() TryPROforFREE LearnPythonInteractively



請為這篇文章評分?