Python - Working on a file

3

I'm starting in Python and every sentence I try to write gives me an error.

I created a archivo.txt with a fasta sequence that I downloaded, with its spaces and numbers.

Now I try to work on it, making small changes, in plan to remove spaces, eliminate car jumps.

I know how to do it if I copy the sequence above, but open it from another file no.

fichero = open ('/ruta del archivo.txt')

for linea in fichero:

    a=fichero.replace('\n','')

    b=a.replace(' ','')

    dna = re.sub("[0-9]", "", b)

print dna

Can there be an error in the names I'm assigning?

    
asked by Lorena 15.05.2016 в 21:03
source

1 answer

2

With open you are opening the file and what you get is a reference to it; but the reading is done with each iteration of the loop where each line is put in variable linea . The .replace() you have to use on each line read, not on the reference to the file.

I give you an example to read FASTA files:

def readGenome(filename):
    genome = ''
    with open(filename, 'r') as f:
        for line in f:
            # ignore header line with genome information
            if not line[0] == '>':
                genome += line.rstrip()
    return genome

genome = readGenome('lambda_virus.fa')
    
answered by 16.05.2016 / 00:41
source