如何使用 python 将所有 txt 文件分类到终端?

How can i cat all txt files to terminal using python?

我想从文件夹中 cat txt 文件,cat 结果应该显示在终端中(很明显)。我试过使用 listdir() 但它不起作用。需要一些帮助!

一个简单的实现使用 glob 生成扩展名为 .txt 的文件的绝对路径,在一个循环中读取文件并将其打印在标准输出上:

import glob,sys
for filepath in sorted(glob.glob("path/to/directory/*.txt")):
    with open(filepath) as f:
        sys.stdout.write(f.read())

使用 fileinput 允许逐行读取所有文件,可能内存占用更少且更短:

import glob,sys,fileinput

for f in fileinput.input(sorted(glob.glob("path/to/directory/*.txt"))):
    sys.stdout.write(f)

请注意 sorted 可以更好地确保以确定的顺序处理文件(某些文件系统不遵守该顺序)

sys.stdout.write(f) 仍然逐行写入,但正如评论所建议的那样,您可以通过使用 shutil.copyfileobj(f,sys.stdout)

来提高性能并且不会使用太多内存

只需在终端中使用命令"cat *"

或者,如果您想在 python 中完成:

import os
allTextFileContents = os.popen("cat *").read();
print(allTextFileContents);

您还可以对内容执行其他操作,因为它存储为变量!