-1

Simply put, I'm using Tkinter for my graphic interface, and want to:

  1. Read a text file.

  2. Print "test" to make sure everything's going smoothly.

  3. Clear the current list box.

  4. Fill the listbox with every line in the text file.

  5. Print "another test" to make sure I've made it this far.

    with open("chat.txt", "a+") as chat:
       print("test")
       listbox.delete(first=0, last="END")
    
       for x in chat:
          listbox.insert("END", x)
          print("another test")
    

"test" gets printed but "another test" does not.

MagorTuga
  • 33
  • 6
  • 1
    Opening the file in `a+` mode puts the file pointer at the end of the file, so there is nothing to read. – John Gordon Jan 07 '21 at 22:10
  • So, which one should I use? I thought it was the best, because it allowed reading, writing, and created a new one if one didn't already exist. – MagorTuga Jan 07 '21 at 22:13
  • To read existing file content and also write new content, use `r+`. – John Gordon Jan 07 '21 at 22:21
  • Nothing in the question suggests there is any need to write to the file at all. Just use `open("chat.txt")`. – chepner Jan 07 '21 at 22:33
  • That's probably a bad idea. If he doesn't understand why `"a+"` leaves the pointer at the end of the file to start, he's likely to inadvertently overwrite some part of the file if the pointer *does* get moved earlier. – chepner Jan 07 '21 at 22:36

1 Answers1

0

First, you have to place the file cursor at the beginning of the file. Or just use the r+ mode as suggested above.

Second, variables in upper case often refer to constants, in this case END imported from tkinter.

from tkinter import *

root = Tk()
listbox = Listbox(root)
listbox.pack(expand=True, fill='both', padx=10, pady=10)

with open("chat.txt", "a+") as chat:
   print("test")
   listbox.delete(first=0, last=END)
   chat.seek(0) # Position file cursor at beginning of file

   for x in chat:
      listbox.insert(END, x)
      print("another test")
figbeam
  • 7,001
  • 2
  • 12
  • 18