交错文本文件内容的最Pythonic方式是什么?

Fra*_*ank 3 python

Python问题:

如果我有一个文件列表,如何从每个文件打印#1行,然后打印#2行等?(我是一个Python新手,显然......)

例:

file1:
foo1
bar1

file2:
foo2
bar2

file3:
foo3
bar3
Run Code Online (Sandbox Code Playgroud)

功能调用:

names = ["file1", "file2", "file3"]
myfct(names)
Run Code Online (Sandbox Code Playgroud)

期望的输出:

foo1
foo2
foo3

bar1
bar2
bar3
Run Code Online (Sandbox Code Playgroud)

这就是我做到的,但我确信有更优雅的Pythonic方式:

def myfct(files):
    file_handlers = []
    for myfile in files:
        file_handlers.append(open(myfile))
    while True:
        done = False
        for handler in file_handlers:
            line = handler.readline()
            eof = len(line) == 0 # wrong
            if (eof):
                done = True
                break
            print(line, end = "")
        print()
        if done == True:
            break
Run Code Online (Sandbox Code Playgroud)

PS:我正在使用Python 2.6 from __future__ import print_function.

Ign*_*ams 8

for lines in itertools.izip(*file_handlers):
  sys.stdout.write(''.join(lines))
Run Code Online (Sandbox Code Playgroud)

  • 只需将`sys.stdout.write()`更改为`print()`即可. (2认同)