编写fasta文件,只创建最后一行

时间:2016-11-28 10:23:38

标签: python bioinformatics fasta

这是我编写的用于将dna序列翻译为蛋白质序列的代码。该功能有效,但当我尝试输出蛋白质序列时,只有最后一个序列出现在文件中。

def translate(dna_seq): #create function
    "this function translates a dna sequence into a single letter code amino acid sequence"
    #create dictionary for genetic code codon:amino acid
    gencode = {'TTT':'F', 'TTC':'F', 'TTA':'L', 'TTG':'L', 'CTT':'L', 'CTC':'L', 'CTA':'L', 'CTG':'L', 'ATT':'I', 'ATC':'I', 'ATA':'I', 'ATG':'M', 'GTT':'V', 'GTC':'V', 'GTA':'V', 'GTG':'V', 'TCT':'S', 'TCC':'S', 'TCA':'S', 'TCG':'S', 'CCT':'P', 'CCC':'P', 'CCA':'P', 'CCG':'P', 'ACT':'T', 'ACC':'T', 'ACA':'T', 'ACG':'T', 'GCT':'A', 'GCC':'A', 'GCA':'A', 'GCG':'A', 'TAT':'Y', 'TAC':'Y', 'CAT':'H', 'CAC':'H', 'CAA':'Q', 'CAG':'Q', 'AAT':'N', 'AAC':'N', 'AAA':'K', 'AAG':'K', 'GAT':'D', 'GAC':'D', 'GAA':'E', 'GAG':'E', 'TGT':'C', 'TGC':'C', 'TGG':'W', 'CGT':'R', 'CGC':'R', 'CGA':'R', 'CGG':'R', 'AGT':'S', 'AGC':'S', 'AGA':'R', 'AGG':'R', 'GGT':'G', 'GGC':'G', 'GGA':'G', 'GGG':'G', 'TAA':'_', 'TAG':'_', 'TGA':'_'}  
    protein_seq = "" #define blank string for protein sequence
    for x in range(0,len(dna_seq),3): #loop to read the dna_seq from the beginning, 0, for entire length of dna_seq, counting by 3
        codon = dna_seq[x:x+3] #estabilishing that each codon is at X base index to 3 indices over, so codon is every 3 letters
        protein_seq += gencode[codon] #adding the amino acid, value, corresponding to the codon, key, from the dict gencode
    return protein_seq 

with open('cDNA_sequences(2).csv', 'r') as file: #open file for reading, 
    for line in file: #create loop to read each line
        data = line.rstrip("\n").split(",") #create list by removing newline and comma
        seq_name = data[0] #sequence name is first column of data
        dna_seq = data[1] #dna base sequence is second column

        protein_seq = translate(dna_seq) #protein sequence function of dna sequence from file

    with open ("protein_sequences.fasta", "w") as outfile: #open file for writing 
        outfile.write(">{}\n".format(seq_name)) #write > and sequence name
        outfile.write("{}\n".format(protein_seq)) #write protein sequence 

导出到文件的所有内容都是1734个序列中的最后一个

1 个答案:

答案 0 :(得分:0)

缩进打印件。
您正在打开/关闭文件的级别打印而不是文件中的每行

with open('cDNA_sequences(2).csv', 'r') as file: #open file for reading, 
    for line in file: #create loop to read each line
        data = line.rstrip("\n").split(",") #create list by removing newline and comma
        seq_name = data[0] #sequence name is first column of data
        dna_seq = data[1] #dna base sequence is second column

        protein_seq = translate(dna_seq) #protein sequence function of dna sequence from file

        with open ("protein_sequences.fasta", "w") as outfile: #open file for writing 
            outfile.write(">{}\n".format(seq_name)) #write > and sequence name
            outfile.write("{}\n".format(protein_seq)) #write protein sequence