amintou amintou - 24 days ago 8
Python Question

Read every line on multiple files simultaneously

I have 'n' ".txt" files in a folder, I wanna open them at the same time and read every first line of each file in a loop, then every second line ...

My files are written like this :

0
1
0
1
1
0
0
0


I've used

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


Thanks

Answer Source

If you don't want to read the contents of every file in memory,

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

if __name__ == '__main__':
    file_handles = {filename: open(filename, 'r') for filename in FILES}
    while file_handles:
        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)