Issue :
You are facing this problem since csv_reader
is ITERATOR (Please google this concept :) ).
Iterator is object which has "next
" method available. When you execute csv_reader = csv.reader(file)
, it creates csv_reader
as iterator. csv_reader.next()
will give you one line at the time. But as the lines are over, there is no way to restart it again.
Please check below :
C:\Users\dinesh\Desktop>python
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (
AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> file = open('a.csv','r')
>>> csv_reader = csv.reader(file)
>>>
>>> dir(csv_reader)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__has
h__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr_
_', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'dialect', 'line
_num', 'next']
>>>
>>> csv_reader.next()
['7765', '1256', 'http://hshihwih.com', '0']
>>>
>>> csv_reader.next()
['12453', '18978', 'http://shjhjkshd.com', '1']
>>>
>>> csv_reader.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
In your code, when first iterations are done for data
is done, again it can't come back for target
due to reason I explained aboved.
Solution :
Collect data in one loop as below :
import csv
file = open('a.csv','r')
csv_reader = csv.reader(file)
data = []
target = []
for x in csv_reader:
data.append(x[-1])
target.append(x[-2])
print data
print len(data)
print target
print len(target)