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]
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()
感谢您的所有答案。 @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()