Why the following python code does not print to a file

from sys import stdout stdout = open('file', 'w') print 'test' stdout.close() 

creates a file but contains nothing.

I had to use

 import sys sys.stdout = open('file', 'w') print 'test' sys.stdout.close() 

But can not from ... import... make this name available? Why do I still need to use sys.stdout instead of stdout ?

+7
source share
1 answer

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' # 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() 

Conclusion

It works...

 from sys import stdout stdout = open('file', 'w') stdout.write('test') stdout.close() 
+8
source

All Articles