如果你想写新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
第一小盘强烈行数从第二块不同。 (7行比3行)
这个例子的输出将是chunk1.txt:
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