0

My question is simple. I am saving my listbox into txt file according to below code:

def file_save():
    global filename
    if filename == '':
        filename = filedialog.asksaveasfile(mode='w', defaultextension=".txt")
    if filename is not None:
        for i in textentry.get(0,END):
            filename.write(i+"\n")

My list box contains multiple lines like

aa
bb
cc

And my txt output is like that also.

But when I load this txt file into my empty listbox. It shows

aabbcc

My loading code is below:

def file_open():
    global filename
    filename = filedialog.askopenfile(mode='r+', filetypes =[('Txt', '*.txt')])
    if filename is not None:
        t = filename.read()
        textentry.delete(0, 'end')
        for item in t:
            textentry.insert(END, item)
        #textentry.insert(END, t)
        textentry.focus()

I tried adding for item in t: and it shows

a
a
b
...

textentry.insert(END, t) shows aabbcc

I need to show my loaded txt file as

aa
bb
cc

Thank you

TheLizzard
  • 7,248
  • 2
  • 11
  • 31
  • 2
    Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – Thingamabobs Apr 18 '21 at 14:30

1 Answers1

1

Use readlines instead of read:

from tkinter import filedialog, Listbox, Tk

top = Tk()
textentry = Listbox(top)

filename = filedialog.askopenfile(mode='r+', filetypes =[('Txt', '*.txt')])
if filename is not None:
    t = filename.readlines()
    textentry.delete(0, 'end')
    for item in t:
        textentry.insert('end', item)
    textentry.focus()

textentry.pack()
top.mainloop()
David Meu
  • 1,527
  • 9
  • 14