【发布时间】: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