python csv 模块reader后转换为列表

时间:2017-08-31 09:18:35   收藏:0   阅读:655
  fh = open("mylist_wincsv.csv", ‘rt‘)  
  reader = csv.reader(fh)       
  data = list(reader)        
  print "Data cells from CSV:"        
  print data[0][1], data[1][1]        
  print data[0][2], data[1][2]        
  print data[0][3], data[1][3]

  以上是书上的代码。可是无法实现。len(list(reader)) =0

查询官网知道。reader=csv.reader(fh) 

Return a reader object which will iterate over lines in the given csvfilecsvfile can be any object which supports the iterator protocol and returns a string each time its __next__() method is called — file objects and list objects are both suitable

所以尝试代码换下

import csv
fh=open("mylist.csv",‘rt‘)
a=[]
try:
    reader=csv.reader(fh)
    for row in reader:
        a.append(row)



except Exception as e:
    print("Exception is:",e)
finally:
    fh.close()

print(a[1][0])

  这样就可以了

原文:http://www.cnblogs.com/uxiuxi/p/7456389.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!