python skipping a for loop

时间:2015-07-28 23:58:34

标签: python for-loop continue

I'm writing code to find latitudes and longitudes, and calculate a distance within a certain radius of a point, and separate the two files.

For the first 5 iterations, the program runs fine, but after that, the program does not run through the inner tooltipContent(function(key, y, e, graph) { return 'Some String' }) loop. I have stepped through the code, it just steps over the for loop. It seems to be dependent on what I set variable for to. If radius is smaller, it will allow fewer iterations of the inner radius loop.

I'm afraid this might be a problem of how I'm reading in the file. I believe that after the 5th iteration the for is blank, but I can't figure out how to fix it.

infile_2

1 个答案:

答案 0 :(得分:3)

直接的答案是当你在for x in f样式循环中遍历a文件时,python实际上是在跟踪你进入文件的距离。因此,如果在到达断点之前对内部for循环执行10次迭代,则下次尝试使用infile_2迭代文件时,您将在文件中开始10行!

听起来好像在你的情况下,通过第三次迭代你已经读完整个文件,所以infile_2迭代器只会在外部for循环的所有后续迭代中位于文件的末尾。简单的解决方法是在内部for循环运行之前执行infile_2.seek(0)。这将重新定位infile_2以再次查看文件的开头。 ...

这一切都很好,花花公子,但我想向你提出几点建议:

  1. 当您打开文件时,请使用this SO post中的with open("test.txt","r") as f。这使您无需记住显式关闭文件,因为它在块结束时隐式关闭。

  2. 通常最好将文件读入列表,进行计算,然后一次性写入结果。这使您的代码更有条理(也更容易阅读),并且还可以避免错误,例如您遇到的错误。

  3. 为了说明这些策略,我将在您的代码示例中阅读文件:

    def main(): 
        global infile_1, infile_2
    
        with open("great_lakes_sample.csv", "r") as infile_1:
            #List comprehension to format all of the lines correctly
            infile1_lines = [line.strip().replace("\"", "").split(",") for line in infile_1] 
    
        with open("university_FIPS.csv", "r") as infile_2:
            #List comprehension to format all of the lines correctly
            infile2_lines = [line.strip().split(",") for line in infile_2]
    
        #Both files are automatically closed when their respected with blocks end.