How to Use Python Csv Dictreader - Linux Hint
文章推薦指數: 80 %
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
延伸文章資訊
- 1csv — CSV File Reading and Writing — Python 3.10.7 ...
The csv module implements classes to read and write tabular data in CSV format. It allows program...
- 2【Day 2】常見的資料格式(1/3) - CSV
CSV 的全名是Comma Separated Values,顧名思義就是用**逗點(,)**分隔的資料。 ... Python 有提供標準的模組來操作CSV 資料,這邊就介紹一些常用到的API。
- 3How to Use Python Csv Dictreader - Linux Hint
The DictReader () is used to read the file of the csv in the format of the dict object. Let's dis...
- 4csv --- CSV 文件读写— Python 3.8.14 說明文件
csv 模块中的 reader 类和 writer 类可用于读写序列化的数据。也可使用 DictReader 类和 DictWriter 类以字典的形式读写数据。 也參考. 该实现在“Pytho...
- 5CSV in python · 菜鳥的SaaS之旅 - wirelessr
要讀一個csv format的字串而不是檔案需要透過 StringIO ,也就是將string當成檔案。在python2和python3稍微有點差別: try: # for Python 2.x...