在Python中从.txt文件读取特定部分的数据

2024-09-30 20:23:31 发布

您现在位置:Python中文网/ 问答频道 /正文

>gene1
ATGATGATGGCG
>gene2
GGCATATC
CGGATACC
>gene3
TAGCTAGCCCGC

这是我正在读的文本文件。 我想读取不同字符串中的每个基因,然后将其添加到列表中 有以“>;”字符开头的标题行可以识别这是一个基因的开始还是结束

with open('sequences1.txt') as input_data:
    for line in input_data:
            while line != ">":
                list.append(line)
    print(list)

打印时,列表应显示

list =["ATGATGATGGCG","GGCATATCCGGATACC","TAGCTAGCCCGC"]

Tags: 字符串列表inputdataline基因list文本文件
3条回答

您的代码中有多个错误,请看这里:

with open('sequences1.txt', 'r') as file:
    list = []
    for line in file.read().split('\n'):
            if not line.startswith(">") and len(line$
                list.append(line)
    print(list)

试试这个:

$ cat genes.txt
>gene1
ATGATGATGGCG
>gene2
GGCATATC
CGGATACC
>gene3
TAGCTAGCCCGC


$ python
>>> genes = []
>>> with open('genes.txt') as file_:
...   for line in f:
...     if not line.startswith('>'):
...       genes.append(line.strip())
...
>>> print(genes)
['ATGATGATGGCG', 'GGCATATC', 'CGGATACC', 'TAGCTAGCCCGC']
with open('sequences1.txt') as input_data:
    sequences = []
    gene = []
    for line in input_data:
        if line.startswith('>gene'):
            if gene:
                sequences.append(''.join(gene))
                gene = []
        else:
            gene.append(line.strip())
sequences.append(''.join(gene)) # append last gene
print(sequences)

输出:

['ATGATGATGGCG', 'GGCATATCCGGATACC', 'TAGCTAGCCCGC']

相关问题 更多 >