而不是使用write()
,Python 2 和 3 中写入文本文件的其他方法是什么?
file = open('filename.txt', 'w')
file.write('some text')
您可以使用print_function
未来进口 http://docs.python.org/library/__future__.html得到print()
python2 中 python3 的行为:
from __future__ import print_function
with open('filename', 'w') as f:
print('some text', file=f)
如果您不希望该函数在末尾附加换行符,请添加end=''
的关键字参数print()
call.
但是,请考虑使用f.write('some text')
因为这更加清晰并且不需要__future__
import.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)