Python CSV: Read and Write CSV files - Programiz
文章推薦指數: 80 %
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
延伸文章資訊
- 1如何在Python 中把列表寫入CSV
可以使用Python 列表值來編寫csv 檔案。像csv.writer()、writerow()、pandas 和numpy 庫這樣的方法都是用於這個目的的。
- 2Writing CSV files in Python - GeeksforGeeks
csv.writer class is used to insert data to the CSV file. This class returns a writer object which...
- 3Python 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...
- 4Python 讀取與寫入CSV 檔案教學與範例 - G. T. Wang
這裡介紹如何在Python 中使用 csv 模組,讀取與寫入逗點分隔檔。 ... import csv # 開啟輸出的CSV 檔案 with open('output.csv', 'w', ne...
- 5Writing to CSV in Python - codingem.com
The 4 Steps to Writing a CSV in Python · Open a CSV file in the write mode. This happens using th...