我的看法。有两个问题:您想连接不同的文件,然后重新打印。因此,我们分别执行这两个步骤,以实现一个干净的实现import sys
from itertools import chain
def file_reader(filename):
"Iterate over the lines of file, opening it lazily"
with open(filename) as f:
for i in f:
yield i.rstrip()
filenames = sys.argv[1:]
all_lines = chain(*[ file_reader(fn) for fn in filenames ])
# now all_lines is an iterable that iterates over the all input lines
outf = None
for line in all_lines:
if line.startswith('>'):
# open new file
if outf:
outf.close()
# take the file number from the '>2' line
outf = open('out-%04d.txt' % int(line[1:]), 'w')
# python 2
print >> outf, line
if outf:
outf.close()
运行方式
^{pr2}$
得到out-0001.txt文件>1
AAAAAAAAAAAAAA
CGGGGGGGGGGGGG
DEEEEEEEEEEEEE
AFGGGGGGGGGGGG
DEEEEEEEEEEE
和out-0002.txt>2
AAAABBBBBBBBB
DFFFFFFFFFFFFF
DFFFFFFFSSSS