Python "ValueError: I/O operation on closed file." in nested loop : I'm trying to create an link scraper which worked so far. I only had problems when I was copying multiple lines, then it never stoped inserting these lines. So I wanted to split the mutliple lines into single lines but after creating the for loop which is iterating over the multilines I always get this error: ValueError: I/O operation on closed file.


    import pyperclip
    import datetime


    while True:
        with open("text.txt", "r+") as textfile:
            text = str(pyperclip.paste())
            liste = text.split("\r\n")

            for element in liste:
                for line in textfile:
                
                    if element in line:
                        break
                else: 
                    now = datetime.datetime.now()
                    textfile.write(str(now.day) + "." + str(now.month) + "." +
                                   str(now.year) + " " + str(now. hour) + ":" +
                                   str(now.minute) + " | ")
                    textfile.write(element + "\n")
                    textfile.close()
                    print(element)
         