How to parse csv formatted files using csv.DictReader?

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

CSV, or "comma-separated values", is a common file format for data. The csv module helps you to ... Your Python code must import the csv library. import csv. Usageofcsv.DictReader CSV,or "comma-separatedvalues",isacommonfileformatfordata. Thecsv modulehelpsyoutoelegantlyprocessdatastoredwithinaCSVfile. Alsoseethe csvdocumentation. Thisguideusesthefollowingexamplefile,people.csv. id,name,age,height,weight 1,Alice,20,62,120.6 2,Freddie,21,74,190.6 3,Bob,17,68,120.0 YourPythoncodemustimportthecsvlibrary. importcsv Openthefilebycalling open andthencsv.DictReader. input_file=csv.DictReader(open("people.csv")) Youmayiterateovertherowsofthecsvfilebyiteratingove input_file.(Similarlytootherfiles,youneedtore-openthe fileifyouwanttoiterateasecondtime.) forrowininput_file: printrow Whenyouiterateoveranormalfile,eachiterationoftheloopproducesa singlestringthatrepresentsthecontentsofthatline. WhenyouiterateoveraCSVfile,eachiterationoftheloopproducesa dictionaryfromstringstostrings.Theykeysarethenamesofthe columns(fromthefirstrowofthefile,whichisskippedover),andthe valuesarethedatafromtherowbeingread.For example,theaboveloopprintsthefollowing: {'age':'20','height':'62','id':'1','weight':'120.6','name':'Alice'} {'age':'21','height':'74','id':'2','weight':'190.6','name':'Freddie'} {'age':'17','height':'68','id':'3','weight':'120.0','name':'Bob'} ToprinttheentirecontentsoftheDictReader,youmightexecutethefollowingcode: Finally,hereisacompleteexampleusageofcsv.DictReaderusingpeople.csv.This examplefindstheoldestpersonwithinthefileandthatperson'sage. importcsv input_file=csv.DictReader(open("people.csv")) max_age=None oldest_person=None forrowininput_file: age=int(row["age"]) ifmax_age==Noneormax_age



請為這篇文章評分?