1

I got the following error in my python code:

     TypeError: writelines() requires an iterable argument

I know it's error submited before but I can't got my answer . here is my code :

 def Normaliaze(dataset):    
      final_list=[]
      twoCol = [ item[0:2] for item in dataset]
      labels = [ item[2] for item in dataset]
      twoColData = preprocessing.scale(float64(twoCol ))

      for x,y in itertools.izip(twoColData,labels):
         temp =[]
         temp.append(x[0])
         temp.append(x[1])
         temp.append(y)
         final_list.append(temp)

      caving = open('/home/nima/Desktop/ramin-ML-Project/caving.txt','w')

      for item in final_list:
         if item[2] == 'caving':            
             caving.writelines(item[0])
             caving.writelines('\t')
             caving.writelines(item[1])
             caving.writelines('\n')
Nima
  • 490
  • 2
  • 10
  • 19

2 Answers2

4

You are using writelines() but passing in one item at a time; file.writelines() expects an iterable (something producing a sequence of 0 or more values) instead.

Use file.writeline() (singular) instead, or even better, just file.write():

caving.write(item[0])
caving.write('\t')
caving.write(item[1])
caving.write('\n')

If you are writing a Tab-separate file, you might want to use the csv module instead:

import csv

def normalize(dataset):    
    twoCol = [item[:2] for item in dataset]
    labels = [item[2] for item in dataset]
    twoColData = preprocessing.scale(float64(twoCol))

    with open('/home/nima/Desktop/ramin-ML-Project/caving.txt', 'wb') as caving:
        writer = csv.writer(caving, delimiter='\t')

        for data, label in itertools.izip(twoColData, labels):
            if label == 'caving':
                writer.writerow(data)

This produces the same output, but with less hassle.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

For strings you should write(), while for a sequence of strings you can use writelines(). See the post here. For instance, you try to write the sting '\t' with writeline().

Community
  • 1
  • 1
Roman
  • 156
  • 5