1. 程式人生 > >python csv 模塊reader後轉換為列表

python csv 模塊reader後轉換為列表

ble app try proto which -m 實現 all supports

  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 csvfile. csvfile 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])

  這樣就可以了

python csv 模塊reader後轉換為列表