Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to parse a file with a limited knowledge in python with some loops but seems I'm doing something wrong. I want to get the genes(sp...) if values in lst are between the numbers in the middle. Here's the file (ast.txt):

SPAC212.11  1   5662    -1

SPAC212.10  5726    6331    -1

SPAC212.09c 7619    9274    1

SPNCRNA.70  11027   11556   -1

SPAC212.08c 11784   12994   1

SPAC212.07c 13665   14555   1

SPAC212.12  15855   16226   1

SPAC212.06c 18042   18306   1

and here's my code:

lst=[2,6000,18042,11784]

f=open('asd.txt','r')

g=f.readlines()[0:]

for line in g:
    for s in lst:
        if (s)>=int(line.split()[1:2]) and (s)<=int(line.split()[2:3]):
            line.split()[0:1]
share|improve this question
1  
Please make use of the code markers function in the editor and separate your code from the file data. –  RyPeck 43 mins ago
 
I didn't know that function but im trying know.Thanks. –  mehmet 39 mins ago
add comment

1 Answer

up vote 1 down vote accepted

A few suggestions:

output = [] # lines to keep; empty for now

with open("asd.txt", 'r') as f: # use with to handle file open/close

    for line in f: # iterate through lines

        line = line.strip().split() # split the line once

        if any(int(line[1]) <= n <= int(line[2]) for n in lst): # check

            output.append(line[:]) # add copy to output

# use lines in output

Note that this will keep the line in split() form as a list of str values, e.g.:

output == [['SPAC212.07c', '13665', '14555', '1'], ...]
share|improve this answer
 
Well i tried your code but output list was empty,i don't know why.But i changed your code just a little and it works good. for n in lst: if int(line[1]) <= n <= int(line[2]): output.append(line[0:1]) Thanks a lot! –  mehmet 9 mins ago
 
Apologies, edited to copy the whole line. Note that line[0:1] == line[0]. –  jonrsharpe 3 mins ago
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.