Halawa
Halawa

Reputation: 1241

csv files in python

i am working on a machine leaning project and here is my code

import csv
import numpy as np
import string
from sklearn.ensemble import RandomForestRegressor

def main():
alchemy_category_set = {}
#read train data
train = []
target = []
with open("/media/halawa/93B77F681EC1B4D2/GUC/Semster 8/CSEN 1022 Machine Learning/2/train.csv", 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
reader.next() #skip the header
for row in reader:
  line = row[3:len(row)-1]
  train.append(line)
  target.append(row[len(row)-1])
  if row[3] not in alchemy_category_set:
    alchemy_category_set[row[3]] = len(alchemy_category_set)

#read valid data
valid = []
valid_index = []
with open("/media/halawa/93B77F681EC1B4D2/GUC/Semster 8/CSEN 1022 Machine Learning/2/test.csv", 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
reader.next() #skip the header
for row in reader:
  line = row[3:len(row)]
  valid.append(line)
  valid_index.append(row[1])
  if row[3] not in alchemy_category_set:
    alchemy_category_set[row[3]] = len(alchemy_category_set)


if __name__=="__main__":
main()

the reading of the test.csv is not working although it is working with the traing,csv , when i run it gives me

/usr/bin/python2.7 /home/halawa/PycharmProjects/ML/train.py
Traceback (most recent call last):
File "/home/halawa/PycharmProjects/ML/train.py", line 68, in <module>
main()
File "/home/halawa/PycharmProjects/ML/train.py", line 26, in main
reader.next() #skip the header
StopIteration
Process finished with exit code 1

the problem is with reading the csv file , any help would be appreciated .

Upvotes: 0

Views: 553

Answers (1)

lanenok
lanenok

Reputation: 2749

I think you just forgot indentation after opening test file. Namely, after with open line the next 8 lines (each of these lines) should be indented with 2 more space .

By the way, it is highly recommended to indent with 4 spaces, not just 2. And it should be consistent in your file

Upvotes: 1

Related Questions