python - 同时读取多个文件的每一行

标签 python text file-io

我的文件夹中有“n”个“.txt”文件,我想同时打开它们并循环读取每个文件的第一行,然后每隔一行......

我的文件是这样写的:

0
1
0
1
1
0
0
0

我用过

file = fileinput.input(files=("text_{}.txt".format(i)))
for line in file:
    for ch in line:
        print file.readline()

谢谢

最佳答案

如果你不想读取内存中每个文件的内容,

FILES = ['1.txt', '2.txt', '3.txt']

if __name__ == '__main__':
    file_handles = {filename: open(filename, 'r') for filename in FILES}
    while 1:
        for filename, file in file_handles.items():
            line = next(file, None)
            if line is not None:
                line = line.rstrip('\n')
                print(line)
            else:
                file.close()
                # file_handles.pop(filename)
        if line is None:
            break

关于python - 同时读取多个文件的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46391572/

相关文章:

c - C 中的 Hexdump 文本和二进制文件

java - 即使文件存在 FileNotFoundException

C# 超大字符串操作(内存不足异常)

python - Pandas:即使日期已经在月末,也能正确获取业务月末日期

python - 如果函数给出的值非常接近 0,则对函数内部的数字进行舍入

python - 如何继承logging.Handler来记录到GtkTextView?

R - 如何提取字符串和空行之间的文本?

python - 将任务安排为从同步代码运行事件循环

CSS 停止文本大小调整到最底部

c++ - 读取 Intel Hex 文件以对 C++ 进行排序