如何逐行遍历文件?

时间:2022-07-20 15:24:54

I have files with lines of input which I compare to eachother. I have simplified my code alot and obviously it isnt in working python but the main bits of important are the first line for iteration and the else clause, both of which are the ones used. The rest are just to show I wish to continue on with the data if it passes the Comparison code.

我有输入行的文件,我相互比较。我已经简化了我的代码很多,显然它不在工作python中,但重要的主要部分是迭代的第一行和else子句,两者都是使用的。其余的只是为了表明我希望继续使用数据,如果它通过比较代码。

for read1, read2 in itertools.izip(input_file1, input_file2):  
    {CODE FOR COMPARISON}
    if matched:
        Worked = read1+read2
    else:
        print to output_file2
        break
    {CONTINUE ANALYSIS OF 'Worked'}
    print Worked to output_file1

I assumed adding a print to file and break would solve the issue however it doesn't break the for loop so the next iteration occurs, it just breaks it. Is there anyway to use a command like break to move onto the next iteration of lines in both input files?

我假设添加一个打印到文件和break将解决问题,但它不会破坏for循环所以下一次迭代发生,它只是打破它。无论如何使用像break这样的命令移动到两个输入文件中的下一行迭代?

Thanks, Tom

谢谢,汤姆

1 个解决方案

#1


0  

Is there anyway to use a command like break to move onto the next iteration of lines in both input files?

无论如何使用像break这样的命令移动到两个输入文件中的下一行迭代?

You are looking for the continue statement rather than the break statement:

您正在寻找continue语句而不是break语句:

break exits the loop whereas continue just moves onto the next iteration

break退出循环,而continue继续进入下一次迭代

for read1, read2 in itertools.izip(input_file1, input_file2):  
    {CODE FOR COMPARISON}
    if matched:
        Worked = read1+read2
    else:
        print to output_file2
        continue
    {CONTINUE ANALYSIS OF 'Worked'}
    print Worked to output_file1

See https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

请参阅https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

#1


0  

Is there anyway to use a command like break to move onto the next iteration of lines in both input files?

无论如何使用像break这样的命令移动到两个输入文件中的下一行迭代?

You are looking for the continue statement rather than the break statement:

您正在寻找continue语句而不是break语句:

break exits the loop whereas continue just moves onto the next iteration

break退出循环,而continue继续进入下一次迭代

for read1, read2 in itertools.izip(input_file1, input_file2):  
    {CODE FOR COMPARISON}
    if matched:
        Worked = read1+read2
    else:
        print to output_file2
        continue
    {CONTINUE ANALYSIS OF 'Worked'}
    print Worked to output_file1

See https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

请参阅https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops