Python-用列表推导同时打开一堆文本文件

时间:2014-06-13 19:09:45

标签: python loops text gensim

我正在研究一种带有gensim的LDA模型。为此,我基本上打开文本文件,构建字典,然后运行模型。

要打开我使用的文件:

files = [codecs.open(infile, 'r', 'utf-16', 'ignore') for infile in sample_list] 

其中sample_list是文件路径列表。我需要使用codecs.open,因为文本是使用不同的语言(我没有更新Python)。

我的问题是我不知道在使用它们之后如何关闭所有文件。有任何想法吗?我尝试过几件事。我不能在这里使用常规循环,因为我的后续步骤是:

texts = [" ".join(file.readlines()[0:]) for file in files]

当我使用超过5,000个文件时,我收到错误''IOError:[Errno 24]打开的文件太多''我想我可以一次打开一些文件,加入它们,关闭它们,然后重复。此外,保持文件打开是不好的。 谢谢!

1 个答案:

答案 0 :(得分:4)

def read_contents(filename):
    with codecs.open(filename, 'r', 'utf-16', 'ignore') as infile:
        return ' '.join(infile)

texts = [read_contents(filename) for filename in sample_list]

使用with相当于:

def read_contents(filename):
    try:
        infile = codecs.open(filename, 'r', 'utf-16', 'ignore')
        return ' '.join(infile)
    finally:
        infile.close()

finally关键字确保close()无论如何都会被执行,即使脚本在try内引发错误。

相关问题