help with loops

Tim Chase python.list at tim.thechases.com
Mon Mar 6 16:16:55 CET 2006


> I have two files and I want to pull out lines from file 2
> if certain conditions are found if file 1.


Well, I'm not quite sure from your description of the 
problem if you want to compare every line in file1 against 
every line in file2, or if you just want to compare line1 of 
file1 with line1 of file2; line2 of file1 with line2 of file2...

For the former, you'd use something like

for line1 in file1.readlines():
	list1 = line1.split(",")
	for line2 in file2.readlines():
		list2 = line2.split(",")
		if (list1[3] == list2[6] and list1[4] == list2[8]):
		        print line

For the latter, you have to consider the case where one file 
is longer than the other, unless you happen to know that 
they're the same length.  If they are, or you just want the 
min length of whichever is shorter, you could do something like

for line1,line2 in zip(file1.readlines(), file2.readlines()):
	list1 = line1.split(",")
	list2 = line2.split(",")
	if list1[3] == list2[6] and list1[4] == list2[8]:
	        print line

Just a few thoughts you might try tinkering with to see if 
they do something close to what you want.

-tkc







More information about the Python-list mailing list