如何在多个文件夹中阅读多个文本文件?

时间:2016-05-08 09:08:16

标签: python directory

我在文本文件中有语料库,这些文件在几个文件夹中分成几个文本文件。我正在做的是计算它们的熵,但很难在一个文本文件中连接它们。我所做的就像下面一样。

filenames = ['BrownA1.txt', 'BrownB1.txt', 'BrownC1.txt'.....]
with open("C:/Python27/TRAINING.txt", 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)

但这种方法需要花费很多时间。我有几百个txt文件要读。 像这样。 C:/ Python27 / acq / 000916~012897,C:/ Python27 / alum / 0009945~012875,C:/ Python27 / barley / 0010141~0011953~如你所见,有近30个文件夹就像那种格式,在它们下面是至少30个txt文件。 有没有有效的方法来阅读它们?

1 个答案:

答案 0 :(得分:0)

使用os.walkhttps://docs.python.org/2/library/os.html#os.walk)递归到文件夹树中。当然,如果将所有文本文件(或包含文本文件的文件夹)放入空的根文件夹中,这将非常有用。显然你使用的C:\ Python27似乎不是最佳选择。

因此,如果您的文本文件收集在C:\ path \ to \ root \ folder的(子文件夹)中,您可以执行以下操作:

import os
with open('c:/path/to/output/file.txt', 'w') as outfile:
    for root, dirs, files in os.walk("c:/path/to/root/folder"):
        for f in files:
            if os.path.splitext(f)[-1] == ".txt":
                with open(os.path.join(root, f), "r") as infile:
                    for line in infile:
                        outfile.write(line)
相关问题