将控制台输出写入python中的文件

时间:2013-06-08 11:22:14

标签: python python-3.x

我希望将控制台输出写入文件, 如何将控制台输出重定向到 文件'c1.txt'? 请帮助。 这是我的代码:

from collections import Counter
from glob import iglob
import re
import os

def removegarbage(text):
    # Replace one or more non-word (non-alphanumeric) chars with a space
    text = re.sub(r'\W+', ' ', text)
    text = text.lower()
    return text

topwords = 100
folderpath = 'path/to/directory'
counter = Counter()
for filepath in iglob(os.path.join(folderpath, '*.txt')):
    with open(filepath, 'r') as filehandle:
        counter.update( removegarbage(filehandle.read()).split() )

for word, count in counter.most_common(topwords):
    print ('{}: {}'.format(count, word))

0 个答案:

没有答案