How to open and manipulate multiple text files all at the same time after selecting them with tkinter? How to open and manipulate multiple text files all at the same time after selecting them with tkinter? tkinter tkinter

How to open and manipulate multiple text files all at the same time after selecting them with tkinter?


You are not working with each file name within the list. So instead you need to run a for loop over your list created from askopenfilenames().

According to the tooltip in my IDE askopenfilenames() returns a list.

def askopenfilenames(**options):    """Ask for multiple filenames to open    Returns a list of filenames or empty list if    cancel button selected    """    options["multiple"] = 1    return Open(**options).show()

I changed your variable filename to filenames as it is a list and this makes more sense. Then I ran a for loop over this list and it should work as desired.

Try this below code.

import refrom Tkinter import *from tkFileDialog import askopenfilenamesfilenames = askopenfilenames()for filename in filenames:    f = open(filename, "r")    lines = f.readlines()    f.close()    f = open(filename, "w")    for line in lines:        line = re.sub('<(.|\n)*?>', "", line)        f.write(line)    f.close()

With a couple of if statements we can prevent the most common errors that may come up if you select nothing or select file types that are not compatable.

import refrom Tkinter import *from tkFileDialog import askopenfilenamesfilenames = askopenfilenames()if filenames != []:    if filenames[0] != "":        for filename in filenames:            f = open(filename, "r")            lines = f.readlines()            f.close()            f = open(filename, "w")            for line in lines:                line = re.sub('<(.|\n)*?>', "", line)                f.write(line)            f.close()