How to Use Python Csv Dictreader - Linux Hint

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

The DictReader () is used to read the file of the csv in the format of the dict object. Let's discuss how to use the DictReader () method in python. TheDictReader()isusedtoreadthefileofthecsvintheformatofthedictobject.Let’sdiscusshowtousetheDictReader()methodinpython. Beforewestartthemaincourseofthisarticle,let’sfirstunderstandwhatacsvfileis. WhatisaCSV(CommaSeperatedValues)File?: ACSVisafileinwhichdataisintheformofacomma-separatedorotherdelimiteruserchoiceseparated.Thesefileshaveextensioncsv.Thiscsvfileismostlyusedindataanalytics.Apartfromthedataanalytics,thecsvfileisalsousedinthee-commerceapplicationbecauseit’sveryeasytohandleinalldifferentprogramminglanguages. 1.DictReader()methodtoreadparticularcolumnname: CSVfile:Thebelowisatest.csvfile.ThiscsvfilewewillbereadfromtheDictReader().Inthisprogram,wearenotgoingtoreadthewholecsvfiledatainsteadonlytheMonthcolumnasshowninthebelow: "Month","1958","1959","1960" "JAN", 340, 360, 417 "FEB", 318, 342, 391 "MAR", 362, 406, 419 "APR", 348, 396, 461 "MAY", 363, 420, 472 "JUN", 435, 472, 535 "JUL", 491, 548, 622 "AUG", 505, 559, 606 "SEP", 404, 463, 508 "OCT", 359, 407, 461 "NOV", 310, 362, 390 "DEC", 337, 405, 432 Pythoncode: 123456789importcsv withopen('test.csv')asf:   DictReader_obj=csv.DictReader(f)   foriteminDictReader_obj:     print(item['Month']) Output: JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC Line1:Weimportthecsvmodule. Line2to5:Weopenthetest.csvfileasf,andthenwecreateanobjectoftheDictReader.Theobject(DictReader_obj)thendisplaysallthedataofthecolumnMonth. 2.DictReader()methodtoreadcsvfileasadictionary: Now,wearegoingtoseehowwecanreadthecsvasadictionaryformat.Weareusingthesametest.csvfileasweusedbefore.Theexampleforthismethodisgivenbelow: 123456789importcsv withopen('test.csv')asf:   DictReader_obj=csv.DictReader(f)   foriteminDictReader_obj:     print(dict(item)) Output: {'Month':'JAN','"1958"':' 340','"1959"':' 360','"1960"':' 417'} {'Month':'FEB','"1958"':' 318','"1959"':' 342','"1960"':' 391'} {'Month':'MAR','"1958"':' 362','"1959"':' 406','"1960"':' 419'} {'Month':'APR','"1958"':' 348','"1959"':' 396','"1960"':' 461'} {'Month':'MAY','"1958"':' 363','"1959"':' 420','"1960"':' 472'} {'Month':'JUN','"1958"':' 435','"1959"':' 472','"1960"':' 535'} {'Month':'JUL','"1958"':' 491','"1959"':' 548','"1960"':' 622'} {'Month':'AUG','"1958"':' 505','"1959"':' 559','"1960"':' 606'} {'Month':'SEP','"1958"':' 404','"1959"':' 463','"1960"':' 508'} {'Month':'OCT','"1958"':' 359','"1959"':' 407','"1960"':' 461'} {'Month':'NOV','"1958"':' 310','"1959"':' 362','"1960"':' 390'} {'Month':'DEC','"1958"':' 337','"1959"':' 405','"1960"':' 432'} Line1:Weimportthecsvmodule. Line2to5:Weopenthetest.csvfileasanf,andthenwecreateanobjectoftheDictReader.Theobjectwillcontinuetoiteratetillthedata.Thecsv.DictReader()willreturneachrowoftypeanOrederedDict,soweconverteachOrderedDicttyperowtoadictusingthetypecastmethod.Theobjectreaderthendisplaysallthedatainthedictionaryformat,asshownintheaboveoutput. But,ifyouareusingthelatestpython,thendicttypeconversionisnotrequired,asweareusingtypecastinlinenumber5oftheaboveprogramexample. 3.DictWriter()method: DictWritermethodisapartoftheDictReadermethodwhereithelpstowritethedictionaryformatdatatothecsvfile.Sointhisprogram,wewillseehowwecanwritethedictionarydatatothecsv. 1234567891011importcsv withopen('output.csv',"w",newline="",encoding="utf-8-sig")asoutfile:   writer=csv.DictWriter(outfile,["FirstName","LastName"])   writer.writeheader()   new_row={"FirstName":"Linux","LastName":"Hint"}   writer.writerow(new_row) Ouput: FirstName,LastName Linux,Hint Line3to7:Weopentheoutput.csvfileinthewritingmode(‘w’).ThenwepasstheheaderofthecsvintheformofthelisttotheDictWriterwhilecreatingtheobjectitself.Wehavetotellthecolumnnamesofthecsvtotheobjectbeforewritingtothecsv;else,itwillgenerateanerrorbecausethentheobjectwillnotbeabletounderstandthekeynamesofthedictionary.Inline6,wecreatedonedictobjectandpassedittothewriterowobjecttowriteintothecsvfile. Theoutputshowsthatourdataissuccessfullywrittenonthecsvfile. 4.DictWriter()methodtowritealistofdictionarydatatocsv: Inthisprogram,wewillseehowwecanwritealistofdictionarydatatocsv.Inthepreviousexample,wehavewrittenonlysingledictionarydatatocsvforunderstandingtheconcept.Butwewritecsvwithhugedataindailylife.Sowearegoingtoseethatscenariointhisexample. 12345678910111213141516171819importcsv withopen('output.csv','w')ascsvfile:   col=['FirstName','LastName','GradePoint']   writer=csv.DictWriter(csvfile,fieldnames=col)   writer.writeheader()   writer.writerows([{'GradePoint':'B','FirstName':'Jeorge','LastName':'Belly'},     {'GradePoint':'A','FirstName':'Krishna','LastName':'Kumar'},     {'GradePoint':'C','FirstName':'Sheon','LastName':'Shaiyer'},     {'GradePoint':'B','FirstName':'Janny','LastName':'Jeus'},     {'GradePoint':'A','FirstName':'Sham','LastName':'Sharma'}]) Output: FirstName,LastName,Grade Jeorge,Belly,B Krishna,Kumar,A Sheon,Shaiyer,C Janny,Jeus,B Sham,Sharma,A Line3to11:Weopentheoutput.csvfileinthewritingmode(‘w’).ThenwepasstheheaderofthecsvintheformofthelisttotheDictWriterwhilecreatingtheobjectitself.Wehavetotellthecolumnnamesofthecsvtotheobjectbeforewritingtothecsv;else,itwillgenerateanerrorbecausethentheobjectwillnotbeabletounderstandthekeynamesofthedictionary.Inline7,wecreatedalistofdictionaryobjectsandpassedittothewriterowsobjecttowriteallthedataintothecsvfileatonce. Theoutputshowsthatourdataissuccessfullywrittenonthecsvfile. Conclusion:Inthisarticle,wehavelearnedhowtousethemethodsDictReader()andDictWriter().Wehavealsoseenthewaytowritealistofdictionaryobjectstocsvatonce.Themaindifferencewhenwewritealistofdictionariesorasingledictionaryobjectismethodwriterows.Weusedthewriterowsmethodwhenwehadmorethanonedataandthewriterowwhenwehadonlysingledata. Abouttheauthor ShekharPandey Viewallposts RELATEDLINUXHINTPOSTS PyTorchTutorialKerasTutorialt-SNESklearnKNNinSklearnCrossValidationinSklearnPandasUnionPandasrolling().apply()Function



請為這篇文章評分?