【问题标题】:Continuously read the first 3 lines in python [closed]连续阅读python中的前3行[关闭]
【发布时间】:2012-11-30 09:31:53
【问题描述】:

我有一个大文件,我想从中读取前 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

【问题讨论】:

  • 当然,你想读就读。你试过什么?
  • “new.txt 文件中的第二个输出”是什么意思?这会覆盖第一个输出,还是附加到它?这与一次复制六行有什么不同?

标签: python python-2.7 python-2.6


【解决方案1】:

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

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]

【讨论】:

  • @surya 然后把列表写出来...!?
【解决方案2】:

文件是迭代器,因此您只需将输入按三个项目分组即可。

iterttools module 带有一个用于对迭代器进行分组的方法:

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))

【讨论】:

    【解决方案3】:

    您还可以使用 f.tell()

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-05
      • 2015-01-26
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      相关资源
      最近更新 更多