0

出力を task1.txt にリダイレクトしようとしています。通常の印刷機能は完全に機能しますが、テキストは 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))
4

1 に答える 1

3

再割り当てしないでくださいsys.stdout。代わりに、関数fileのオプションを使用します。print()

with open('C:\\Dropbox\\Python\\task1.txt','w') as output:
    print ("".join(lines[i] for i in selected), file=output)
于 2012-09-02T09:08:24.250 に答える