您的位置:首页 > 编程语言 > Python开发

CSVs in Python

2016-07-22 20:34 260 查看
#Representing a CSV as  a   list   of  rows 

#Option 1: Each  row is  a  list 

csv=[['A1','A2','A3'],

          ['B1','B2','B3']]

#Option 2:Each row is a dictionary

csv=[{'name1':'A1','name2':'A2','name3','A3'},

           {'name1':'B1','name2':'B2','name3':'B3'}]

#to read in the student enrollments and print out the first record

########the first way

import unicodecsv

enrollments=[]       ##first,I creat a list of enrollments

f=open('enrollments.csv','rb')   ## Then,I open the file.The mode,rb,here,means that the file will be opened for reading,and the b flag changes the 

                                                    format of  how the file is read.The CSV documentation page mentions that I need to use this  when i use this  library

reader=unicodecsv.DictReader(f)  ###DictReader which means each row will be a dictionary,I chose this since our data does have  a header row,and

                                                    this will allow me to refer to each colum by its name,rather than its number.Now the reader won't  actually be a list of rows.

                                       instead it will be something called  interator.---is that the interator let's you writer a for  loop to access each element,but only once

for row in reader:

    enrollments.append(row)

f.close()

enrollments[0]

############the second way

import unicodecsv

with open('enrollments.csv','rb') as f:

    reader=unicodecsv.DictReader(f)

    enrollments=list(reader)

enrollments[0]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: