Search code examples
pythonexcelloopsflagsxlrd

Alternative to using flags when iterating through objects in python


I have a script that compares values between two .xls sheets using xlrd. By default it lets me look for similarities, and writes them to a txt file. If I pass an in an argument, I can look for devices unique to each .xls, and write those to txt file. Right now, I iterate through the rows in each .xls, and mark a flag as True when it finds a similarity between the two files. It will only write hosts from the first sheet when the flag is marked False. Here is the bit of code with flags:

else:
    for row1 in range(sheet1.nrows):
        inboth = False
        for row2 in range(sheet2.nrows):
            if sheet2.row_values(row2)[0].split(".")[0] == sheet1.row_values(row1)[0].split(".")[0]:
                inboth = True
        if not inboth:
            outfile.write(sheet1.row_values(row1)[0].split(".")[0] + ",File1\n")
    for row2 in range(sheet2.nrows):
        inboth = False
        for row1 in range(sheet1.nrows):
            if sheet1.row_values(row1)[0].split(".")[0] == sheet2.row_values(row2)[0].split(".")[0]:
                inboth = True
        if not inboth:
            outfile.write(sheet2.row_values(row2)[0].split(".")[0] + ",File2\n")

Is there a more efficient way to do this without using the "inboth" flag? Is there a solution where I don't need to iterate through both sheets twice?


Solution

  • What you want is the Python set data type. http://docs.python.org/library/sets.html Iterate through the first file and put all the devices you find in set s then put all the devices from the second filw in set t. then do:

    r = s.symmetric_difference(t)

    r will have the list of devices in one but not both files.