0

Newbie to python. Learning how the Lambda function works with printing. I have managed to output the print to a .txt document using sys.stdout, but when I do I am only getting the last variable in the fields. How are all fields captured? What am I missing?

    from tkinter import *

    fields = 'First Name', 'Last Name', 'Organization', 'Tax Exeption',

    def fetch(entries):
        for entry in entries:
            field = entry[0]
            text = entry[1].get()
            sys.stdout = open('file.txt', 'w')
            print('%s: "%s"' % (field, text))
            sys.stdout.close()

    def makeform(root, fields):
        entries = []
        for field in fields:
            row = Frame(root)
            lab = Label(row, width=15, text=field, anchor='w')
            ent = Entry(row)
            row.pack(side=TOP, fill=X, padx=5, pady=5)
            lab.pack(side=LEFT)
            ent.pack(side=RIGHT, expand=YES, fill=X)
            entries.append((field, ent))
        return entries

    if __name__ == '__main__':
        root = Tk()
        root.title('Order Info')
        ents = makeform(root, fields)
        root.bind('<Return>', (lambda event, e=ents: fetch(e)))
        b1 = Button(root, text='Print',
                    command=(lambda e=ents: fetch(e)))
        b1.pack(side=LEFT, padx=5, pady=5)
        b2 = Button(root, text='Quit', command=root.quit)
        b2.pack(side=LEFT, padx=5, pady=5)
        root.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685

1 Answers1

0

The problem is that you are opening the file each time in the for loop. You want to open it once, write all then close.

def fetch(entries):
    sys.stdout = open('file.txt', 'w')
    for entry in entries:
        field = entry[0]
        text = entry[1].get()
        print('%s: "%s"' % (field, text))
    sys.stdout.close()

Another problem is that by opening the file in write mode it will truncate the file. More info on file modes here.

So if you want to be able to add multiple groups of data to the same file you will need to use the mode a to append to the file.

sys.stdout = open('file.txt', 'a')

Additionally, you can also do without sys.

def fetch(entries):
    with open('file.txt', 'a') as fout:
        for field, entry in entries:
            text = entry.get()
            fout.write('{} "{}"\n'.format(field, text))
            #fout.write(f'{field} "{text}"\n') #3.6+
Community
  • 1
  • 1
Steven Summers
  • 5,079
  • 2
  • 20
  • 31