The problem is this: print equivalent to sys.stdout.write() .
So, when you do from sys import stdout , the stdout variable will not be used by print .
But when you do
import sys print 'test'
it actually writes to sys.stdout , which points to the file you opened.
Analysis
from sys import stdout stdout = open('file', 'w') print 'test'
import sys sys.stdout = open('file', 'w') print 'test'
Conclusion
It works...
from sys import stdout stdout = open('file', 'w') stdout.write('test') stdout.close()
ATOzTOA
source share