0

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)
  • So just call the function. What do you want the `delimiter` parameter to be? – quamrana May 06 '22 at 17:29
  • I've used this line for the button that calls the function, `btn_compile = tk.Button(frm_buttons, text="Compile Lines", command=split_lines(cleaned_data, "/"))` but I can't get it to run off the filepath that was already read in `open_file()`. Delimiter is "/". – Chaotic.Python May 06 '22 at 17:31
  • Please fix the indentation of the posted code. – norie May 06 '22 at 18:19
  • If you are really talking about having a button run a function, you should look at answers to this [question](https://stackoverflow.com/questions/5767228/why-is-the-command-bound-to-a-button-or-event-executed-when-declared) – quamrana May 07 '22 at 11:07
  • No not quite. I'm looking for how I can link the variable `lines` in `split_lines()` to the opened file in `open()`. – Chaotic.Python May 10 '22 at 17:06
  • So just call the function with `lines` as the first parameter. – quamrana May 10 '22 at 18:11

1 Answers1

0

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, '/')
quamrana
  • 37,849
  • 12
  • 53
  • 71