Search code examples
pythonpython-3.xsettext-files

How to not make text file whos lines I split not have duplicate output using a set


Hello so I have a file that I have split into containers and are pulling from them. I confirmed that all of them are the same and pulling [3] will get me a code and [7] will get me a result. But [7] has lines that repeat and I only want one instance of [7] to show. I'm trying to use sets but I cant find a way to use it. I've looked up sets and understand a bit, but I can't figure out how to use it. Thank you for reading.

f = open(textfile.txt", "r")

error = f.readlines()

for l in error:
    s = l.split()
    if "70" in s[3]:
        print("Error:", s[3], "Color:", s[7])

f.close()

Right now it will show up as:

Error: 701 Color: Purple
Error: 701 Color: Purple
Error: 702 Color: Pink
Error: 702 Color: Pink
Error: 702 Color: Pink
Error: 705 Color: Black
Error: 705 Color: Black
Error: 705 Color: Black
Error: 705 Color: Black

But I want it to show up as:

Error: 701 Color: Purple
Error: 702 Color: Pink
Error: 705 Color: Black

Solution

  • Use set is a wise choice, it won't contain duplicated elements.

    errorMessages = set()
    
    f = open("textfile.txt", "r")
    
    error = f.readlines()
    
    for l in error:
        s = l.split()
        if "70" in s[3]:
            errorMessages.add(f"Error: {s[3]} Color: {s[7]}")
    
    f.close()
    
    for msg in errorMessages:
        print(msg)