【问题标题】:Need to Read a Line Ahead Without Reading Two Lines at a Time (Python)需要提前读取一行而不是一次读取两行(Python)
【发布时间】:2021-03-11 21:44:09
【问题描述】:

我正在编写一个 python 代码,它逐行读取文本文件并打印该行和下一行,如果该行以“>”开头并且下一行以“G”开头。为了说明,我想要以下输入文件...

>mm10_sample_name_here
GATCGATGCTGCTAGTAGCATG
>mm10_sample_name_here
>mm10_sample_name_here
AATCGATGCTGCTAGTAGCATG
>mm10_sample_name_here
>mm10_sample_name_here
>mm10_sample_name_here
GATCGATGCTGCTAGTAGCATG

输出为...

>mm10_sample_name_here
GATCGATGCTGCTAGTAGCATG
>mm10_sample_name_here
GATCGATGCTGCTAGTAGCATG
>mm10_sample_name_here
GATCGATGCTGCTAGTAGCATG

我已经尝试在下面使用 next()...

original_file = 'test_input_file.txt'
file_destination = 'test_output_file.txt'

import os
if os.path.exists(file_destination):
  os.remove(file_destination)

f=open(original_file, 'r+')

for line in f:
  try:
    line2 = next(f)
  except StopIteration:
    line2 = ""
  if line2.startswith("G") and line.startswith(">"):
    with open(file_destination, "a") as myfile:
       myfile.write(line)
       myfile.write(line2)

但是,它一次读取输入文件两行,这意味着一旦一行不符合 if 条件,所有其他行都不匹配。对此的任何帮助都会很棒。谢谢。

【问题讨论】:

    标签: python loops iteration readline next


    【解决方案1】:

    正如您所发现的,您的解决方案不起作用。您在每次迭代中将生成器推进两个项目(因为您调用了 next())。您需要使用一种策略仅将生成器推进一次。一种是在循环时保持状态,例如

    previous_line = ""
    for line in f:
      if line.startswith("G") and previous_line.startswith(">"):
        ...
      previous_line = line
    

    您也可以保留 next() 函数并使用例如while True:,但当有多行以“>”开头时,请注意边缘情况。

    【讨论】:

    • 您一次移动生成器一行并检查前一行的策略效果很好。谢谢。
    【解决方案2】:

    这是我对您想要做什么的最佳猜测。你忽略了边缘条件,比如如果你在第一行得到一个G,那么它必然是不完整的。

    这是一种简单的程序方法,它在“G”上触发,并且仅在前一行是 > 时才打印。这样比向前看更容易。

    for line in open(file):
        if line.startswith('>'):
            last_line = line
    
        elif line.startswith('G') and last_line:
            print(last_line)
            print(line)
            last_line = None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-01
      • 2018-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多