如何在python中将输出保存到文件中?

时间:2018-02-06 02:32:04

标签: python

我的代码为:

handle = open('abc.txt','r')
tokens = []
sys.stdout=open("test.txt","w")
for line in handle:
    tokens+=word_tokenize(line)
print(tokens)
sys.stdout.close()

当我尝试运行它时,我的计算机需要很长时间(超过40分钟),但如果不保存在文件中则只需几秒钟。以什么方式可以更改代码,以便在最短时间将输出写入文件?

1 个答案:

答案 0 :(得分:-1)

你正在寻找这样的东西:

from itertools import chain
with open('abc.txt') as infile:
    tokens = list(chain(*map(word_tokenize, infile)))
with open("test.txt","w") as outfile:
    outfile.write("\n".join(tokens))

您的令牌每行将保存一个令牌。

相关问题