0
我想重定向輸出到task1.txt。正常的打印功能完美地工作,但文本不能用sys.stdout重定向。Python 3:sys.stdout不工作
import random
import sys
num_lines = 10
# read the contents of your file into a list
sys.stdout = open('C:\\Dropbox\\Python\\task1.txt','w')
with open('master.txt', 'r') as f:
lines = [L for L in f if L.strip()] # store non-empty lines
# get the line numbers of lines that are not marked
candidates = [i for i, L in enumerate(lines) if not L.startswith("*")]
# if there are too few candidates, simply select all
if len(candidates) > num_lines:
selected = random.sample(candidates, num_lines)
else:
selected = candidates # choose all
# print the lines that were selected
# write.selected(sys.stdout)
print ("".join(lines[i] for i in selected))
# Mark selected lines in original content
for i in selected:
lines[i] = "*%s" % lines[i] # prepend "*" to selected lines
# overwrite the file with modified content
with open('master.txt', 'w') as f:
f.write("".join(lines))
爲什麼你不只是使用'out.write'其中'out'是你的輸出文件?重定向'sys.stdout'對我來說聽起來像一個醜陋的黑客。 –
更重要的是,當您重新分配sys.stdout時,您只會將其重新分配給將來查找sys.stdout的程序的任何部分。打印功能還沒有stdout的句柄,我認爲它甚至不可能使用sys.stdout,因爲打印功能是用C編寫的。 換句話說:sys.stdout不是stdout。 sys.stdout *點*到標準輸出。替換sys.stdout不會以您期望的方式重定向stdout。 –