I've been writing the code for lines and I think i've finally started to figure it out. I'm having some trouble with making the lines into a variable and then comparing them. I'm not sure that this code works, so if anyone can help me fix it or just general improvements, please tell me.

        file1 = open("file1.txt", "r")
    file2 = open("file2.txt", "r")

    for line in file1:
        x = line
        for line in file2:
            y = line
            if x = y:
                return x
                return y
  • what are you trying to do are you trying to compare the two files ? or you want to search for every word in in file1 into file2? Jan 14, 2018 at 14:47
  • @aa-Ahmed-aa I am trying to compare the lines in each file.
    – Joel Banks
    Jan 14, 2018 at 16:33

1 Answer 1


When your code hits return, it instantly leaves the current function.

But you have more problems: Your inner loop reads the file, and on next iteration of the outer loop, there's no more content left, you would have to reset the in-file position to re-read the file.

To avoid having to re-read the file over and over, read both files into memory, and compare them there in another loop (no nesting required if you use Python's in operator). You might find a list or maybe a set useful for line storage.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .