2 回答

TA贡献1829条经验 获得超7个赞
只有strings当您看到一个新的时才追加到,>但在最后一个序列之后没有。
这是一个重构,希望它也更加地道。
strings = []
sequence=''
with open('/Users/vivianspro/Downloads/rosalind_cons (5).txt', 'r') as file:
for line in file:
line = line.rstrip('\n')
if line.startswith('>'):
if sequence != "":
strings.append(sequence)
sequence = ""
else:
sequence+=line
# After the last iteration, append once more if we have something to append
if sequence:
strings.append(sequence)

TA贡献1921条经验 获得超9个赞
由于 FASTA 文件包含以下格式的数据:
>ID1
seq_1
>ID2
seq_2
...
根据您的代码,如果您的行>只包含一个,那么您尝试追加序列。这意味着,当您迭代 ID_2 时,您正在添加 ID_1 的序列。
要解决此问题,您可以执行以下操作:
for line in file:
line = line.strip()
if '>' in line: # Line 1
line = file.readline().strip()
# print(line)
strings.append(line)
上面的示例使用了这样一个事实,即在 FASTA 文件中,序列直接出现在包含>字符的 ID 之后(您可以更改第 1 行,以便它只检查第一个字符, line[0] == ">")。
添加回答
举报