python csv2libsvm.py: AttributeError: '_csv.reader' object has no attribute 'next'
Asked Answered
C

2

55

I want to convert a csv file into sparse format file with csv2libsvm.py (https://github.com/zygmuntz/phraug/blob/master/csv2libsvm.py).

The CSV file contains 37 attributes + the label (last column). it doesn't contain header or index. Exp of the 1st row: 63651000000.0,63651000000.0,153.1,0,0,0,0,0,0,5,1,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1

When entring the following command line : python csv2libsvm.py Z.csv data.txt 38 1

I got the following error:

Traceback (most recent call last):
  File "csv2libsvm.py", line 47, in <module>
    headers = reader.next()
AttributeError: '_csv.reader' object has no attribute 'next'

Do you have any idea about the problem ?

Corney answered 13/3, 2017 at 15:20 Comment(0)
J
94

This is because of the differences between python 2 and python 3. Use the built-in function next in python 3. That is, write next(reader) instead of reader.next() in line 47. In addition, you should open the file in the text mode. So, change line 47 as i = open( input_file, 'r' ).

Jerri answered 13/3, 2017 at 15:27 Comment(3)
So i modified the csv2libsvm.py: 41 i = open( input_file, 'r' ) 42 o = open( output_file, 'wb' ) 44 reader = csv.reader( i ) 46 if skip_headers: 47 headers = next(reader) but i have the following error : Traceback (most recent call last): File "csv2libsvm.py", line 54, in <module> label = line.pop( label_index ) IndexError: pop index out of rangeCorney
It is another problem! label_index should be smaller than the number of elements in each line. Try to investigate the value of label_index.Jerri
Yes thank you, i have another error : Traceback (most recent call last): File "csv2libsvm.py", line 57, in <module> o.write( new_line ) TypeError: 'str' does not support the buffer interface So, i modified the 59 line : o.write( bytes(new_line, 'UTF-8') ) , It works but i got a sparse file containing 1 only row that coreesponds to the last row of csv file!!!!Corney
F
41

For Python 3.x:

Use next(reader) instead of reader.next()

Foggia answered 27/11, 2017 at 21:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.