2012-09-02 5 views
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)) 
+0

왜 당신은 그냥 사용하지 않는를''출력 파일은 out'입니까? 'sys.stdout'을 리다이렉션하는 것은 나에게 못생긴 해킹처럼 들린다. –

+0

더 중요한 것은 sys.stdout을 재 할당 할 때 나중에 sys.stdout을 조회하는 프로그램의 모든 부분에 대해서만 sys.stdout을 재 할당한다는 것입니다. print 함수는 stdout에 핸들을 가지고 있지 않다. print 함수가 C로 작성되었다는 것을 고려해도 sys.stdout을 사용하지는 않을 것 같다. 즉, sys.stdout은 stdout이 아니다. sys.stdout *은 stdout을 가리 킵니다. sys.stdout을 대체하면 예상대로 stdout이 리디렉션되지 않습니다. –

답변

3

sys.stdout을 다시 할당하지 마십시오. 대신, print() functionfile 옵션 사용 : 어디 out.write`

with open('C:\\Dropbox\\Python\\task1.txt','w') as output: 
    print ("".join(lines[i] for i in selected), file=output) 
관련 문제