CSVs in Python 1

本文介绍了两种将CSV文件转换为内存中数据结构的方法:一种是使用列表来表示每行数据;另一种是利用字典来表示,便于通过列名访问数据。通过示例展示了如何使用`unicodecsv`库读取CSV文件并将其转换为这两种形式。

#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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值