from sys import stdout
stdout = open('file', 'w')
print 'test'
stdout.close()
确实创建了文件,但它不包含任何内容。
我不得不使用
import sys
sys.stdout = open('file', 'w')
print 'test'
sys.stdout.close()
但是 from ... import...
不会自动使名称可用吗?为什么我仍然必须使用 sys.stdout
而不是 stdout
?
最佳答案
问题是这样的:print
等同于 sys.stdout.write()
。
因此,当您执行 from sys import stdout
时,变量 stdout
将不会被 print
使用。
但是当你这样做的时候
import sys
print 'test'
它实际上写入了指向您打开的文件
的sys.stdout
。
分析
from sys import stdout
stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the terminal
stdout.close()
import sys
sys.stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the file
sys.stdout.close()
结论
这有效...
from sys import stdout
stdout = open('file', 'w')
stdout.write('test')
stdout.close()
关于python - 为什么以下 python 代码不打印到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544893/