Skip to content Skip to sidebar Skip to footer

Reading Two Files By Comparing All Lines Of File 2 With Each Line Of File 1

I'm trying to read two files and comparing two columns with dates in them and if the dates are the same, then I want to compare two values corresponding to the dates. I want to rea

Solution 1:

What happens is that, when python is iterating over the second file it changes the position of the "cursor" and in the end of the iteration, the cursor location is at the end of the file. So, once you try to go over the file in the second iteration - it immediately terminates (reaches 'StopIteration') as the "cursor" is already at the end of the file.

In the end of the inner loop, you need to return the file current position (cursor for that matter) to the beginning of the file.

So, that will be:

date_location = 0
numeric_value_location = 1
with open('file1.txt') as f1:
with open('file2.txt') as f2:
    for i in f1:
            f1_date = (i.split()[date_location])
            f1_numeric = (i.split()[numeric_value_location])
            for j in f2:
                f2_date = (j.split()[date_location])
                f2_numeric = (j.split()[numeric_value_location])
                if f1_date == f2_date:
                    if f2_numeric < f1_numeric:
                        # Do Something

            f2.seek(0, 0)

I changed the code, hopefully as you requested. Please note:

  1. The split operation can be improved to one line by doing:

    f1_date, f1_number = i.split()
    
  2. The date comparison as I have added per comment request WILL BREAK at some point. The right way to do it, is to format the string date into a datetime object and then do the comparison.

  3. See that i have replaced location 0, 1 indexes with variable to give the code some more meaning - try to use this practice in the future.

Hopefully, that's what you have requested. I highly recommend that you will go over a quick python tutorial just to give yourself a jump-start. Good luck.

See this post for more details: seek() function?

Post a Comment for "Reading Two Files By Comparing All Lines Of File 2 With Each Line Of File 1"