How to parse csv formatted files using csv.DictReader?
文章推薦指數: 80 %
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
延伸文章資訊
- 1Reading CSVs With Python's "csv" Module
Now it's time to start using Python to read CSV files. Here, I've got a simple CSV file that cont...
- 2CSV 檔案操作- Python 教學 - STEAM 教育學習網
Python 的標準函式「csv」提供了操作CSV 檔案的方法,可以針對CSV 檔案進行讀取、寫入或修改,這篇教學將會介紹csv 常用的方法。
- 3How to parse csv formatted files using csv.DictReader?
CSV, or "comma-separated values", is a common file format for data. The csv module helps you to ....
- 4Python DictReader读写csv文件_番茄大圣的博客
准备此文档的示例代码是基于python3.5写的。 使用csv库前,先导入csv库: import csv读取内容假设csv文件的内容如下图所示,DictReader会将第一行的 ...
- 5【Day 2】常見的資料格式(1/3) - CSV
CSV 的全名是Comma Separated Values,顧名思義就是用**逗點(,)**分隔的資料。 ... Python 有提供標準的模組來操作CSV 資料,這邊就介紹一些常用到的API。