gpt4 book ai didi

python - 如何在 python 2.x 和 3.x 中直接打印到文本文件?

转载 作者:太空狗 更新时间:2023-10-29 17:21:41 25 4
gpt4 key购买 nike

除了使用 write(),在 Python 2 和 3 中写入文本文件的其他方法是什么?

file = open('filename.txt', 'w')
file.write('some text')

最佳答案

您可以使用print_function future import从 python2 中的 python3 获取 print() 行为:

from __future__ import print_function
with open('filename', 'w') as f:
print('some text', file=f)

如果您不希望该函数在末尾附加换行符,请将 end='' 关键字参数添加到 print() 调用中。

但是,请考虑使用 f.write('some text'),因为这样更清晰并且不需要 __future__ 导入。

关于python - 如何在 python 2.x 和 3.x 中直接打印到文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10445726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com