pythontkinterdirectorypyinstaller.app

Accessing parallel folder's file in a standalone application


I created a standalone .app application (ToDoList.py / ToDoList.app / ToDoList (Unix Executable)) using pyinstaller. My code uses a file called List.tx to remember and store data which is put on the screen. The program cannot run without the file. I was having problems getting the file to be in the bundle but recently I did some digging into the .app and found that it adds the List.txt file when I use "pyinstaller ToDoList.py --add-data "List.txt:." --windowed". The List.txt file is put in a resource folder parallel to the unix executable and now I need to find a way to access it with my program. I will attach a screenshot and my code. If anyone can help that would be greatly appreciated!

My code:

import tkinter as tk
from tkinter import *
open = open("List.txt", "r+")
file = open.readlines ()
def main ():
    window = Tk()
    window.title("To Do")
    def window_destroy ():
        window.destroy()
    window.geometry ("1440x808+0+0")
    to_do_label = Label(window, text="To Do List:", font=("Times New Roman",25,))
    to_do_label.place(relx=.5, y=20, anchor=CENTER)
    to_do_listbox = Listbox(window, width=50, height=20)
    for i in range(len(file)):
        to_do_listbox.insert(tk.END, str(file[i].strip()))
    to_do_listbox.place(relx=.5, y=230, anchor=CENTER)
    def delete_selected_item ():
        to_do_listbox.delete(tk.ANCHOR)
        for i in range(to_do_listbox.size()):
            open.truncate(i)
        for i in range(to_do_listbox.size()):
            open.write(to_do_listbox.get(i) + "\n")
    add_entry = Entry(window, width=50, font=("Times New Roman", 15))
    add_entry.place(relx=.5, y=425, anchor=CENTER)
    def add_entry_to_list ():
        to_do_listbox.insert(tk.END, add_entry.get())
        for i in range(to_do_listbox.size()):
            open.truncate(i)
        for i in range(to_do_listbox.size()):
            open.write(to_do_listbox.get(i) + "\n")
    add_button = Button(window, text="Add item", width=10, font=("Times New Roman", 15), command=add_entry_to_list)
    add_button.place(relx=.5, y=455, anchor=CENTER)
    delete_button = Button(window, text="Delete item", width=10, font=("Times New Roman", 15), command=delete_selected_item)
    delete_button.place(relx=.5, y=485, anchor=CENTER)
    quit_button = Button(window, text = "Quit", width=5, font=("Times New Roman",15), command=window_destroy)
    quit_button.pack(anchor = "s", side = "right")
    window.mainloop()
main ()

Folder photo


Solution

  • You should be able to use code like this to open your file:

    import sys
    from pathlib import Path
    ...
    if getattr(sys, 'frozen', False):
        folder = Path(sys._MEIPASS)
    else:
        folder = Path(__file__).parent
    open = open(folder / "List.txt", "r+")