, 새 파일에 각 3000 개 기록을 작성하는 itertool's grouper recipe를 사용하여 다음 점진적으로 기록을 생성하는 함수를 정의하고 수 :
#!/usr/bin/env python3
from itertools import zip_longest
with open('input.txt') as input_file:
files = zip_longest(*[generate_records(input_file)]*3000, filevalue=())
for n, records in enumerate(files):
open('output{n}.txt'.format(n=n), 'w') as output_file:
output_file.writelines(''.join(lines)
for r in records for lines in r)
generate_records()
가 하나 개의 레코드를 산출 레코드가 입력 파일의 라인의 반복자는 또한 한 번에 :
from itertools import chain
def generate_records(input_file, start='1\n', eof=[]):
def record(yield_start=True):
if yield_start:
yield start
for line in input_file:
if line == start: # start new record
break
yield line
else: # EOF
eof.append(True)
# the first record may include lines before the first 1\n
yield chain(record(yield_start=False),
record())
while not eof:
yield record()
generate_records()
는이다 발전기는 itertools.groupby()
과 같습니다.
성능상의 이유로 한 번에 여러 줄의 청크를 읽고 쓸 수 있습니다.
출처
2014-10-23 16:19:35
jfs
이런 질문은 쉽게 닫을 수 있습니다. 이를 위해 다양한 옵션을 이용할 수 있습니다. 그러나 코딩/연구 노력을 보여줄 필요가 있습니다. SO는 코드 작성 서비스가 아닙니다. 당신이 뭔가를 가지고 있다면 당신은 당신의 대답을 업데이트하려고 노력했고 우리는 더 기꺼이 도와 줄 것입니다. 이와 같은 질문에 답하는 것도 바람직하지 않습니다. – Matt