0

我有一个巨大的文件,我想从中读取前 3 行并将它们放在另一个文件new.txt中。之后,再读3行,但不要从头开始,应该从第4行开始读3行。

 1st line
 2nd line
 3rd line
 4th line
 5th line
 6th line
 7th line
 8th line
 9th line
 10th line
 ....

文件 new.txt 中的第一个输出将是:

 1st line
 2nd line
 3rd line

文件 new.txt 中的第二个输出将是:

4th line
5th line
6th line
4

3 回答 3

1

像这样的东西 - 请记住,i您可以直接使用 file-obj 而不是。

from itertools import islice

r = range(20)
i = iter(r)

while True:
    lines = list(islice(i, 3))
    if not lines:
        break
    print lines

[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9, 10, 11]
[12, 13, 14]
[15, 16, 17]
[18, 19]
于 2012-11-30T09:36:27.087 回答
0

文件是迭代器,因此您所要做的就是将输入按三个项目分组。

iterttools模块附带了一个用于对迭代器进行分组的方法:

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

现在您可以将输入文件行分组为三组:

with open(inputfilename) as infile:
    for threelines in grouper(3, infile, ''):
        with open(outputfilename, 'w') as outfile:
            outfile.write(''.join(threelines))
于 2012-11-30T09:37:07.553 回答
0

你也可以得到光标位置 f.tell()

您可以将光标移动到文件中的某个位置: f.seek()

在这里查看:http: //docs.python.org/2/library/stdtypes.html#file.seek

于 2012-11-30T09:42:47.037 回答