3

I would greatly appreciate, if you guys could help me with this query.

In my python code, I have opened two files using the open(file, r) function.

Now what I want is, read all the lines of these two files and compare two columns in those data if they match.

I have tried a nested for loop for each line in files

for line in file:
  for lines in file:
     file1 = split(line)
     file2 = split(lines)
     process matching query

However, it does not seem to be working. Could you guys point me in the right direction on how to achieve that?

Thanks

1 Answer 1

4

Iterate through those files simultaneously with zip:

for line1,line2 in zip(file1,file2):

And do all the logic with the lines.

For Python 3.x zip is an iterator, and in Python 2.x you can use izip with the same functionality. Using zip in Python 2.x. will lead to reading all the file contents into memory, while iterator version will advance line by line.

Sign up to request clarification or add additional context in comments.

6 Comments

Hi ovgolovin, thanks for the swift reply. I always assumed that with zip, the list contents had to be the same length. THe two lists that I have are not in the same length, in fact, they contain different data apart from one column where they share the same data (hence the matching).
@user1743872 Inside the for loop split each line, extract the needed column and compare. zip(file1,file2) only allows to advance through files' lines simultaneously.
Hello ovgolovin, do you mean the for loop in my initial post or the for loop that you posted. Thanks in advance
@user1743872 I mean for-loop in my answer. In your answer for each line of the first loop you go through all the lines of the second file in the nested loop.
@user1743872 There is a possibility that I didn't get you question right. It would be better if you proved the example of file1 and file2 content and what you want to achieve.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.