Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python2.x和3.x中直接打印到文本文件?_Python_File_Python 3.x_Stdout_Python 2.x - Fatal编程技术网

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

如何在Python2.x和3.x中直接打印到文本文件?,python,file,python-3.x,stdout,python-2.x,Python,File,Python 3.x,Stdout,Python 2.x,在Python2和Python3中,除了使用write(),还有什么方法可以写入文本文件 file = open('filename.txt', 'w') file.write('some text') 您可以使用print\u函数从python2中的python3获取print()行为: from __future__ import print_function with open('filename', 'w') as f: print('some text', file=f)

在Python2和Python3中,除了使用
write()
,还有什么方法可以写入文本文件

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

您可以使用
print\u函数
从python2中的python3获取
print()
行为:

from __future__ import print_function
with open('filename', 'w') as f:
    print('some text', file=f)
如果不希望该函数在末尾附加换行符,请将
end='
关键字参数添加到
print()
调用中


但是,请考虑使用<代码> f.Wrrad(“某些文本”)< /C> >,因为这更清楚,不需要<代码>“yFuturux> Supp.

”请注意,这是用换行符(<代码> \n < /代码>)打印的。end@jamylak
,end='')
对于
python3
将有帮助为什么您需要其他方法来实现它?一般来说,Python很少有做一件事的方法。这是有意的,也是好的。使用“打印”并不等于写,有细微的区别。
from __future__ import print_function
with open('filename', 'w') as f:
    print('some text', file=f)