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

1

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Or you can use t = filename.read().split("\n")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.