Python Nested loop Executes only once for file iteration

时间:2015-06-25 18:54:43

标签: python file python-2.7 for-loop iteration

#if(len(results) != 0) fr = (open("new_file.txt","r")) fr1 = (open("results.txt","w")) for j in range (len(line_list)): for i, line in enumerate(fr): if(i == line_list[j]):`find the line in the file` fr1.write(FAILURE_STRING+line)`mark the failure` else:`enter code here` fr1.write(line) fr.close() fr1.close() In the above example mmy j loop executes only once. I am trying to mark the failure in the results file. even if my line_list has almost 7 element (line numbers i am suppose to mark the failure for in case of a mismatch), it marks failure for only 1 element. If i take the J for loop inside, it will mark all the failure the there will be the duplicates inside the results file (the number of duplicates of each line would be as same as the number of elements in the line_list )

3 个答案:

答案 0 :(得分:0)

open returns a generator, and you can only iterate over a generator once. You have two options: Reverse the for loops so you only iterate over the file once. for i, line in enumerate(fr): for j in range (len(line_list)): if(i == line_list[j]): #find the line in the file fr1.write(FAILURE_STRING+line)#mark the failure` else: fr1.write(line) Cast your file to a type that's not a generator fr = [i for i in fr]

答案 1 :(得分:0)

If I understood correctly, you have a list of lines that do not match with the ones on a file (new_file.txt), and you want to introduce an error string to those lines. For that, you have to use fr.readlines() on the cycle, which results in something like this line_list = [0, 2, 2, 4] # Example list of lines FAILURE_STRING = "NO" fr = open("new_file.txt", "r") fr1 = open("results.txt", "w") for i, line in enumerate(fr.readlines()): if(i == line_list[i]): fr1.write(FAILURE_STRING+line) else: fr1.write(line) fr.close() fr1.close()

答案 2 :(得分:0)

感谢您的所有答案。 @NightShadeQueen你的回答中的2分帮助我达到了目的。 以下是有效的解决方案:

if(len(results) != 0):

     fr1 = (open("results.txt","w"))
     fr = (open("new_file.txt","r"))
     fr = [i for i in fr]
     for i in range (len(fr)):
         if i in line_list:
             fr1.write(FAILURE_STRING+fr[i])
         else:`enter code here`
             fr1.write(fr[i])            
 fr1.close()