简体   繁体   English

Python 3:sys.stdout无法正常工作

[英]Python 3: sys.stdout not working

i am trying redirect output to task1.txt. 我正在尝试将输出重定向到task1.txt。 normal print funcion working perfectly but text can't be redicted with sys.stdout. 正常的打印功能可以正常工作,但是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))

Don't re-assign sys.stdout . 不要重新分配sys.stdout Instead, use the file option on the print() function : 而是在print()函数上使用file选项:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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