Python 如何读取多个文件夹中的多个文本文件?
我有文本文件中的语料库,这些文本文件分为几个文件夹中的几个文本文件。我正在做的是计算它们的熵,但是很难将它们连接到一个文本文件中。我所做的如下所示Python 如何读取多个文件夹中的多个文本文件?,python,directory,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 in
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/barry/0010141~0011953~正如您所见,类似这种格式的文件夹几乎有30个,下面至少有30个txt文件。
有没有什么有效的方法来阅读它们 使用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)