あなたは、各チャンクのための新しいchunk1.txt ... chunkN.txtを書きたい場合は、あなたがこのような方法でこれを行うことができます:
def chunk_file(name, lines_per_chunk, chunks_per_file):
def write_chunk(chunk_no, chunk):
with open("chunk{}.txt".format(chunk_no), "w") as outfile:
outfile.write("".join(i for i in chunk))
count, chunk_no, chunk_count, chunk = 1, 1, 0, []
with open(name, "r") as f:
for row in f:
if count > lines_per_chunk and row == "\n":
chunk_count += 1
count = 1
chunk.append("\n")
if chunk_count == chunks_per_file:
write_chunk(chunk_no, chunk)
chunk = []
chunk_count = 0
chunk_no += 1
else:
count += 1
chunk.append(row)
if chunk:
write_chunk(chunk_no, chunk)
chunk_file("test.txt", 3, 1)
あなたはどの行を指定する必要がありますチャンクに属し、その後改行が予想される。
Some Data belonnging to chunk 1
Some Data belonnging to chunk 1
Some Data belonnging to chunk 1
Some Data belonnging to chunk 1
Some Data belonnging to chunk 1
Some Data belonnging to chunk 1
More Data, belonnging to chunk 2
More Data, belonnging to chunk 2
More Data, belonnging to chunk 2
最初のチャンクが第二のチャンクからのライン数で強く異なります
あなたはチャンクこのファイルをしてみたいと思います。この例の出力は、chunk1.txtあろう
(7つのライン対3行):
Some Data belonnging to chunk 1
Some Data belonnging to chunk 1
Some Data belonnging to chunk 1
Some Data belonnging to chunk 1
Some Data belonnging to chunk 1
Some Data belonnging to chunk 1
そしてchunk2.txt:
More Data, belonnging to chunk 2
More Data, belonnging to chunk 2
More Data, belonnging to chunk 2
このアプローチは、lines_per_chunkことを前提としていの最小チャンクサイズはなので、チャンクの行数が異なる場合でも動作します。最小のチャンクサイズに達すると、チャンクを終了するための空白行のみを探しています。 上記の例では、最小チャンクサイズにまだ達していないため、2行目に空白行があることは問題ありません。 4行目に空白行があり、それ以降に塊データが続くと、指定された基準(行番号と空白行)が塊だけを識別できないため、問題があります。
カウンタとモジュロを使用します。 –
http://stackoverflow.com/a/544932/568901 – sangheestyle