TypeError: writelines() requires an iterable argument
我的python代码中出现以下错误:
1 | TypeError: writelines() requires an iterable argument |
我知道之前提交的错误,但是我找不到答案。 这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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(' ') |
您正在使用
使用
1 2 3 4 5 | caving.write(item[0]) caving.write('\t') caving.write(item[1]) caving.write(' ') |
如果要编写制表符分隔的文件,则可能要使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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) |
这将产生相同的输出,但麻烦较少。
对于字符串,您应该使用write(),而对于字符串序列,您可以使用writelines()。 在这里查看帖子。 例如,您尝试使用writeline()编写字符串' t'。