Hello everyone, I have two files i.e Rules.txt and Members.txt. I have set different rules for different members. Now i have break down the rules comma seperately using the for loop. I want to compare each index of the 1st file with the respective index of the second file. If it matches so it should do something and vice versa. Please let me know how can i compare them? I am new to python. Thanks in advance.

def compare():
        file1=open("D:\Rules.txt")
        for rules in file1:
                print rules.split(',')
                membersFile=open("D:\Members.txt")
                for members in membersFile:
                                    print members.split(',')


compare()

Recommended Answers

All 3 Replies

The most obvious thing in your code is that "Members.txt" will be opened many times, one for each iteration of the lines in "Rules.txt". This is probably not what you want. You don't need to open each file more than once. To make things easier since you are new to python, you could load the files' content at the beginning with

rule_lines = list(open("Rules.txt"))
member_lines = list(open("Members.txt"))

The next thing is that standard python code is normally indented with 4 space characters and not 8 spaces or tabs. You'd better configure your editor to use 4 space characters.

The missing part in your question is a small exemple of the files content. Without it, it is difficult to understand what you want to compare and your expected result.

I have got the solution for it, not its comparing only one line of the file because i have break the loop, no i want to iter both of my loops to one step ahead and compare the next record to it. How can i increment it? can i use LEN() function on file?

def compare():
        file1=open("D:\Rules.txt")
        for rules in file1:
            rule = rules.split(",")
            break
        membersFile=open("D:\Members.txt")
        for members in membersFile:
            member = members.split(',')
            break
        print rule[0] + "," +member[1] + ","+ rule[1] + "," +member[2] + ","+  rule[2] + "," + member[3]
        if (rule[0]<=member[1]) and (rule[1]<=member[2]) and (rule[2]==member[  3]):
            print member[0] + " is Continued"
        else:
            print member[0] + " is Discontinued"



compare()

If you're using python 3, use

for rule, member in zip(file1, membersFile):
    ...

If you're using python 2, use rather

from itertools import izip

for rule, member in izip(file1, membersFile):
    ...
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.