簡體   English   中英

為什么以下python代碼不打印到文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM