User Tools

Site Tools


script:ex7

Exercise 7 Code

exercise7.py
# Answer key to files notebook, exercise 7
 
#7a
def start_codon(file_name):
    try:
        infile = open(file_name)
    except:
        return 'File could not be opened'
    with infile:
            for line in infile:
                if 'ATG' in line:
                    return line
            return -1
 
start_codon('seq.txt')            
 
 
#7b
def max_from_file(file_name):
    try:
        infile = open(file_name)
    except:
        return -1
    with infile:
        greatest = infile.readline()
        for line in infile:
            if line > greatest:
                greatest = line
        return greatest
 
max_from_file('numbers.txt')
 
 
#7c
def transcriber(input_file_name, output_file_name):
    try:
        infile = open(input_file_name)
        outfile = open(output_file_name, 'w')
    except:
        return -1
    revcomp = ''
    with infile, outfile:
        for line in infile:    
            if '>' in line:
                outfile.write(line)
            else:
                line = line.replace('T', 'U')
                outfile.write(line)
 
transcriber('sequences.txt', 'rna.txt')
 
 
#7d
def rev_comp(input_file_name, output_file_name):
    try:
        infile = open(input_file_name)
        outfile = open(output_file_name, 'w')
    except:
        return -1
    revcomp = ''
    with infile, outfile:
        nts = 'ACTG'
        comps = 'TGAC'
        translation_table = str.maketrans(nts, comps)
        for line in infile:
            line =line.rstrip()
            if '>' in line:
                outfile.write(line + 'rev_comp' + '\n')
            else:
                revcomp = line.translate(translation_table)
                revcomp = revcomp[::-1]
                outfile.write(revcomp + '\n')
 
rev_comp('sequences.txt', 'revcomp_sequencest.txt')
 
 
#7e
def motif_finder_line_by_line(file_name, motif):
    try:
        infile = open(file_name)
    except:
        return -1
    with infile:
        counts = 0
        for line in infile:
            if '>' in line:
                continue
            line = line.rstrip()
            for i in range(0, len(line)):
                if line[i:i+len(motif)] == motif:
                    counts += 1
        return counts
 
motif_finder('c_elegans_chrI.fa', 'tagggcactt')            
 
 
#7f
def motif_finder_all(file_name, motif):
    try:
        infile = open(file_name)
    except:
        return -1
    with infile:
        counts = 0
        file = infile.read()
        file = file.replace('\n', '')
        for i in range(0, len(file)):
            if file[i:i+len(motif)] == motif:
                counts += 1
        return counts
 
motif_finder('c_elegans_chrI.fa', 'tagggcactt')
script/ex7.txt · Last modified: 2018/10/15 16:00 by dokuroot