[英]Writing to a text file program: convert from Python 2 to Python 3
我想从 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)))
到 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()
但它没有保存到文本文件。 我究竟做错了什么?
对于 Python 2,您可以使用 print 写入文件,但在 Python 3 中,您可以这样做:
with open(path, "wb") as f1:
for i in w_vectors:
f1.write(i, " ".join(map(str, numpy.round(w_vectors[i], decimals=6))))
并且在使用“with”时您不必使用 f1.close 因为“with”会自行处理它。
在 Python 3 中使用file
关键字参数进行print
。
print(i, " ".join(...), file=f1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.