【问题标题】:Python 2.7. write following 4 lines out from a huge file蟒蛇 2.7。从一个大文件中写出以下 4 行
【发布时间】:2014-07-09 01:43:03
【问题描述】:

巨大的文件是这样的。

@delimiter...xxxxxxx     1st line
atgccccccccccccccc...    2nd line
+                        3rd line
agtrc!%%^*()_+!...       4th line

这四行继续。分隔符可能在第一行。我想要做的是如果分隔符在第一行,我想写出以下4行。

这是我的代码。

with open("hugefile") as fin, open("hugefile_out") as fout:
    for line in fin:
        if delimiter in line:
            1st_line = line
            2nd_line = fin.next()
            3rd_line = fin.next()
            4th_line = fin.next()
            fout.write(1st_line + 2nd_line + 3rd_line + 4th_line)

通常需要 4 到 5 个小时才能完成这项工作。(我放弃了一个功能。)有没有办法让它更快?(我使用 pypy。)输入文件是 1~100Gb 所以那些重复的代码似乎没有必要。

可能是这样的?

           fout.write(line + fin.next() + fin.next() + fin.next())

提前感谢!

【问题讨论】:

  • 如果分隔符不在第一行会怎样?
  • 那我就不需要了。 :)

标签: python parsing


【解决方案1】:

我会推荐如下方法:

  1. 使用标志表示您已看到分隔符并且当前正在输出行
  2. 使用 索引 了解您输出了多少行
  3. 一旦 index 大于 4 就停止输出行并将 flag 重置为 false(或者,如果您只想找到一组,则可以退出完全迭代)

所以,代码将是这样的:

sawDelim = False
idx = 1
with open("hugefile") as fin, open("hugefile_out") as fout:
    for line in fin:
        if delimiter in line:
            sawDelim = True

        if sawDelim:               
            fout.write(line)
            idx += 1

        # now that we've printed out 4 lines, reset and keep looking
        # (or could also bail if you want to only find one set)
        if (idx > 4):
            idx = 1
            sawDelim = False

【讨论】:

  • 另一种方法:有一个变量用于在此之后输出的行数。如果您看到分隔符,请将其设置为四个。每次输出一行,递减。
  • 谢谢。我会试试看!
猜你喜欢
  • 2014-05-16
  • 1970-01-01
  • 2016-10-17
  • 2015-03-31
  • 2019-06-08
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
相关资源
最近更新 更多