'tkinter, or function to pass filename into variable for use in other function

My code below is to be used in a GUI that has two buttons. One to ask the user to locate a txt file, the other to run a function using that file to clean the data.

However I cannot figure out how to pass the filepath into the split_lines() function in order to run that using that opened txt file.

How can I adjust this to have split_lines() read the already pointed to filepath?

def open_file():
    filepath = askopenfilename(filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
    if not filepath:
        return
    txt_edit.delete("1.0", tk.END)
    with open(filepath, mode="r", encoding="utf-8") as input_file:
        text = input_file.read()
        txt_edit.insert(tk.END, text)
    window.title(f"Linestring Compiler V1.0 - {filepath}")

a = "linestring.txt"
with open(a, 'r') as file:
lines = [line.rstrip('\n') for line in file]

cleaned_data = []
def split_lines(lines, delimiter, remove = '^[0-9.]+$'):
    for line in lines:
        tokens = line.split(delimiter)
        tokens = [re.sub(remove, "", token) for token in tokens]
        clean_list = list(filter(lambda e:e.strip(), tokens))
        cleaned_data.append(clean_list)


Solution 1:[1]

When you're not using a GUI, you just call the function.

You would lay out the code like this:

cleaned_data = []

def split_lines(lines, delimiter, remove = '^[0-9.]+$'):
    cleaned_data.clear()
    for line in lines:
        tokens = line.split(delimiter)
        tokens = [re.sub(remove, "", token) for token in tokens]
        clean_list = list(filter(lambda e:e.strip(), tokens))
        cleaned_data.append(clean_list)
    
a = "linestring.txt"
with open(a, 'r') as file:
lines = [line.rstrip('\n') for line in file]

split_lines(lines, '/')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 quamrana