[英]Why the following python code does not print to file
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
执行操作时, print
不会使用变量stdout
。
但是,当你这样做
import sys
print 'test'
它实际上写入sys.stdout
,它指向您打开的file
。
分析
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.