Search code examples
pythonpython-3.xif-statementline

How to only print or get the second result


I only want to get the second result, which num prints and use it.

savee1 is a .txt file

def copycoordinates():


savee1 = filedialog.askopenfilename(initialdir="C:/USERS/" + username + "/documents/Euro Truck Simulator 2/profiles", title="Choose FIRST File", filetypes=[("sii files", "*.sii")])

savee2 = filedialog.askopenfilename(initialdir="C:/USERS/" + username + "/documents/Euro Truck Simulator 2/profiles", title="Choose SECOND File", filetypes=[("sii files", "*.sii")])

i1 = Label(frame5, text="Chosen FIRST File \n" + savee1)
i1.pack()

i2 = Label(frame5, text="Chosen SECOND File \n" + savee2)
i2.pack()

command=lambda:[save1()]
subprocess.Popen(["C:/SII_Decrypt.exe", savee1])

command=lambda:[save2()]
subprocess.Popen(["C:/SII_Decrypt.exe", savee2])

#time.sleep(1)

with open(savee1, "r+") as save1:

    for num, line in enumerate(save1, 1):
        if "truck_placement:" in line:
            print(num)
            

Solution

  • If you mean you want the second match, you can try:

    with open(savee1, "r+") as save1:
    
    match = 0
    for num, line in enumerate(save1, 1):
        if 'truck_placement:' in line:
            match += 1
            if match == 2
                print(num)
            else:
                continue
    

    The num will print on the second match.

    There are definitely better ways, but this is one of the most easy solution.