简体   繁体   中英

object instance confusion in python

Hi I am trying to manipulate csv file as below

import csv
data=csv.reader(open('data.csv', 'rb'))
a= [row for row in data]
print a

The output of the code is (comma spearated rows--> in list format):

 [['aaaaa', '1234234'], ['bbbb', '2343536'], ['cccc', '5675675'], ['dddd', '2344234'],    ['eeee', '5435324'], ['fffffff', '4353442']]

I will get null value when I use

print [row for row in data] 

I will be helped to have views to this confusion. Thank You

csv.reader returns an iterator which is good for only one pass through the data. You are probably trying to iterate through data twice; the second time, there is no content left in the interator, so

print [row for row in data] 

prints an empty list.

If you want to iterate through data more than once, and have enough memory, you could convert data to a list:

data = list(csv.reader(open('data.csv', 'rb')))

If you don't have enough memory, you would have to parse the CSV again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM