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
延伸文章資訊
- 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...
- 2Reading 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...
- 3CSV in python · 菜鳥的SaaS之旅 - wirelessr
要讀一個csv format的字串而不是檔案需要透過 StringIO ,也就是將string當成檔案。在python2和python3稍微有點差別: try: # for Python 2.x...
- 4csv --- CSV 文件读写— Python 3.8.14 說明文件
csv 模块中的 reader 类和 writer 类可用于读写序列化的数据。也可使用 DictReader 类和 DictWriter 类以字典的形式读写数据。 也參考. 该实现在“Pytho...
- 5CSV 檔案操作- Python 教學 - STEAM 教育學習網
Python 的標準函式「csv」提供了操作CSV 檔案的方法,可以針對CSV 檔案進行讀取、寫入或修改,這篇教學將會介紹csv 常用的方法。