【问题标题】:how can I read multiple text files in several folders? [duplicate]如何读取多个文件夹中的多个文本文件? [复制]
【发布时间】:2016-05-08 09:08:16
【问题描述】:

我有文本文件中的语料库,这些文本文件分为几个文件夹中的几个文本文件。我正在做的是计算它们的熵,但是很难将它们连接到一个文本文件中。我所做的如下所示。

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 文件。 有什么有效的方法来阅读它们吗?

【问题讨论】:

    标签: python directory


    【解决方案1】:

    使用os.walk (https://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)
    

    【讨论】:

      猜你喜欢
      • 2019-11-28
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多