When i print this in the module without printing to file, it prints all values. But when I print it to the designated file, it only prints the first value.

#Create the model base
from sklearn.feature_selection import chi2
import numpy as np
N = 2
for UNSPSC, category_id in sorted(category_to_id.items()):
features_chi2 = chi2(features, labels == category_id)
indices = np.argsort(features_chi2[0])
feature_names = np.array(tfidf.get_feature_names())[indices]
unigrams = [v for v in feature_names if len(v.split(' ')) == 1]
bigrams = [v for v in feature_names if len(v.split(' ')) == 2]

with open('results.csv', 'w') as f:
 print("# '{}':".format(UNSPSC), file=f)
 print("  . Most correlated unigrams:\n. {}".format('\n. '.join(unigrams[-N:])), file=f)
 print("  . Most correlated bigrams:\n. {}".format('\n. '.join(bigrams[-N:])), file=f)

How can i adjust this so that all values get printed onto the file?

  • $\begingroup$ You are writing values to a file, so yes you need to iter over the numpy array. After opening, iter over every Line and write correspondingly $\endgroup$
    – Aditya
    Commented Apr 26, 2018 at 16:38
  • $\begingroup$ Would you be able to provide me the code for that? I tried a few examples from stackoverflow but couldnt get it to work. $\endgroup$
    – Yousuf
    Commented Apr 26, 2018 at 18:16
  • $\begingroup$ If you want to keep that file handy, then you can save it on your hardisk as a numpy array itself, search for . npz (saving numpy array) $\endgroup$
    – Aditya
    Commented Apr 26, 2018 at 18:19

1 Answer 1


Don't forget to open the file first..

Py 2.6

For item in list:
    the_opened_file.write("%s\n" % item)

Py 3.x

with open(filepath,'w') as fileptr:
    for item in list:

If you want to save your list itself, Convert it to numpy format using np.assarray(list) and then use np.save(file,array,....(other opts) and reload it whenever required using np.load()


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.