简体   繁体   中英

Python - list from text file

I am struggling to return a list from a text file, and append new user input values to the list without appending existing values also.

I am using the list in a tkinter combobox, allowing users to type new values to be added to the list. My current code uses a simple text list and is causing problems because of the '\\n' after each line when looking up existing values. It is looking for the value typed/selected (which doesn't have '\\n' until appended to the list, whereas all in the list except last row have '\\n' after them).

listFile.txt is a simple file: (it is a congfiguration file of sorts) item 1 item 2 item 3

My existing code is:

from tkinter import *
from tkinter import ttk

listFile = open('listFile.txt','r')

root = Tk()
root.configure()
varItems = StringVar(root, value='')

class MainWindow(Frame):
    def __init__(self,master = None):
        Frame.__init__(self,master)
        self.master = master
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """Create Window Layout"""
        self.label = Label(self, text="List Items").pack()
        self.itemCombo = ttk.Combobox(self, width = 16, textvariable = varItems)
        self.itemCombo.bind("<Return>", self.itemCombo_onEnter)
        self.itemCombo.bind('<<ComboboxSelected>>',self.itemCombo_onEnter)
        self.itemCombo['values'] = listFile.readlines()
        self.itemCombo.pack()

    def itemCombo_onEnter(self,event):
        varItems.set(varItems.get().lower().strip())
        mytext = varItems.get().strip()
        vals = self.itemCombo.cget('values')
        self.itemCombo.select_range(0,END)
        print(mytext)
        if not vals:
            self.itemCombo.configure(values = (mytext,))
        elif mytext not in vals:
            with open('listFile.txt','a') as f:
                f.write('\n'+ mytext)
                self.itemCombo.configure(values = vals + (mytext,))
                f.close
        return 'break'

app = MainWindow(root)
root.mainloop()

I am open to any suggestions or changes - any help is greatly appreciated!

Inside the onEnter methode change the write code to :

with open('listFile.txt', 'w') as f:
    self.itemCombo.configure(values=vals + (mytext,))
    f.write("\n".join(vals + (mytext,)))
    f.close()

and inside the init methode change listFile.readlines() to [l.strip() for l in listFile.readlines()]

Another easier solution would be too just include a concatenated version of your input to match the search in your file.

mytext = mytext + "\n"
        if not vals:
            self.itemCombo.configure(values = (mytext,))
        elif mytext not in vals:
            with open('listFile.txt','a') as f:
                f.write('\n'+ mytext)
                self.itemCombo.configure(values = vals + (mytext,))
                f.close

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM