【问题标题】:Writing to a text file program: convert from Python 2 to Python 3写入文本文件程序:从 Python 2 转换为 Python 3
【发布时间】:2021-02-04 03:45:21
【问题描述】:

我想从 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 python-3.x python-2.x


【解决方案1】:

对于 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”会自行处理。

【讨论】:

    【解决方案2】:

    在 Python 3 中将file 关键字参数用于print

    print(i, " ".join(...), file=f1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多