简体   繁体   中英

Why the following python code does not print to file

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

does create the file, but it contains nothing.

I had to use

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

But wouldn't the from ... import... automatically make the name available? Why do I still have to use sys.stdout instead of stdout ?

The problem is this: print is equivalent to sys.stdout.write() .

So when you do from sys import stdout , the variable stdout won't be used by print .

But when you do

import sys
print 'test'

it actually writes to sys.stdout which is pointing 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

This works...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM