-1

I want to convert this from Py2:

with open(path, "wb") as f1:
        for i in w_vectors:
            print >>f1, i, " ".join(map(str, numpy.round(w_vectors[i], decimals=6))) 

to Py3:

with open(path, "wb") as f1:
        for i in w_vectors:
            print (f1, i, " ".join(map(str, numpy.round(w_vectors[i], decimals=6))))
    
f1.close()

but it's not saving to the text file. What am I doing wrong?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
KoKo
  • 349
  • 5
  • 24
  • 1
    Does this answer your question? [Python: Open and write to a .txt file](https://stackoverflow.com/questions/34010106/python-open-and-write-to-a-txt-file) – Calaf Oct 21 '20 at 08:53
  • 1
    Does this answer your question? [How to redirect 'print' output to a file using python?](https://stackoverflow.com/questions/7152762/how-to-redirect-print-output-to-a-file-using-python) – Tomerikoo Oct 21 '20 at 09:01

2 Answers2

2

For Python 2 you could use print to write to files but in Python 3 here is how you would do it instead:

with open(path, "wb") as f1:
    for i in w_vectors:
        f1.write(i, " ".join(map(str, numpy.round(w_vectors[i], decimals=6))))

And you do not have to use f1.close when using "with" because "with" takes care of it by itself.

d3corator
  • 1,154
  • 1
  • 9
  • 23
2

Use the file keyword parameter to print in Python 3.

print(i, " ".join(...), file=f1)
Keith
  • 42,110
  • 11
  • 57
  • 76