如何从一个文件夹中读取多个txt文件

How to read multiple txt files from one folder

在任何 python 库中是否有任何方法可以从一个文件夹中读取多个 txt 文件。我有以下代码:

path = '/home/paste/archives'

files = filter(isfile, glob.glob('%s/*'%path))
for names in files:
    try:
        with open(names) as f:
            print (names)
    except IOError as exc:
        if exc.errno != errno.EISDIR:
            raise

但是代码从 "archives" 文件夹中读取所有文件。我只想阅读 .txt 文件。我该怎么办?

您可以使用

限制 glob 搜索
files = filter(isfile, glob.glob('%s/*.txt' % path))

使用以下代码片段,您可以获取给定目录中的所有文件和目录,并仅选择具有 .txt 扩展名的文件和目录:

files = [file for file in os.listdir(path) if file.endswith('.txt')]

如果您在一个文件夹中有很多文件(并且没有要从中获取 .txt 文件的子目录),请考虑我的回答,因为它速度更快。