开发者

nested for loops in Python involving 2 files [duplicate]

开发者 https://www.devze.com 2023-04-01 08:35 出处:网络
This question already has answers here: for loop problem [duplicate] (4 answers) Closed 7 years ago. I have 2 files: one (ranges.txt) with rows that contain 2 tab-delimited integers, and a
This question already has answers here: for loop problem [duplicate] (4 answers) Closed 7 years ago.

I have 2 files: one (ranges.txt) with rows that contain 2 tab-delimited integers, and a second (values.txt) with tab-delimited values, the first of which is an integer. The integers 开发者_JAVA百科in ranges.txt represent the start and end points for a range, and for each of these ranges I want to ask how many of the integers in values.txt fall in this range. As a starting point, I have written this bit of code:

RangesFile = open('ranges.txt', 'r')
ValuesFile = open('values.txt', 'r')
for Line in RangesFile:
    RangesFile.next()
    print Line
    Line = Line.strip('\n')
    RangeValues = Line.split('\t')
    Start = int(RangeValues[0])
    End = int(RangeValues[1])
    print Start
    print End
    for Line in ValuesFile:
        Line = Line.strip('\n')
        ElementList = Line.split('\t')
        SNP = int(ElementList[0])
        print SNP
        print 'yes' if Start <= SNP <= End else 'no'        

RangesFile.close()
ValuesFile.close()

I get the following output for test files with 2 ranges and 2 integers:

1867    4663

1867
4663
1923
yes
10384150
no
15274293    15275591

15274293
15275591
17486938    17490453

The nested loop does not seem to run after the first iteration. What have I done wrong? (I know my code is overly long, but I'm trying to keep things simple as an absolute beginner.) Thanks for your help!


the second for loop reads the whole ValuesFile. after its execution, the file pointer is at the end of the file, and there is no more values to be read from it.

you should reset the ValuesFile file pointer before starting the second for loop to start reading ValuesFile from the beginning again.

0

精彩评论

暂无评论...
验证码 换一张
取 消