BENZINI
BENZINI

Reputation: 13

Python writes the wrong thing in csv

Code:

import tkinter
import csv


def mainapp():
print ('R')

def SigUP():

U = input1.get()
P = input2.get()
R = input3.get()

def P():
    myData = [[U, P, R]]
    myFile = open('csvexample3.csv', 'w')  
    with myFile:  
            writer = csv.writer(myFile)
            writer.writerows(myData)


if U == '' or P == '' or R == '':
    print ('No')
else:
    P()

def LogIN():
U = input1.get()
P = input2.get()
R = input3.get()


main = tkinter.Tk()

realname = tkinter.Label(main, text='Real Name')
input3 = tkinter.Entry(main)
Username = tkinter.Label(main, text='Username')
input1 = tkinter.Entry(main)
Password = tkinter.Label(main, text='Password')
input2 = tkinter.Entry(main, show="*")
SigUp = tkinter.Button(main, text='Join Us Now', command=SigUP)
LogIn = tkinter.Button(main, text='Log In', command=LogIN)

input3.grid(column='2', row='1')
realname.grid(column='1', row='1')
input1.grid(column='2', row='2')
Username.grid(column='1', row='2')
input2.grid(column='2', row='3')
Password.grid(column='1', row='3')
SigUp.grid(columnspan='3', row='5')
LogIn.grid(columnspan='3', row='4')

main.mainloop()

In my csv file, I get this:

Ben4594,<function SigUP.<locals>.P at 0x101d51950>,Ben

I expect that my csv should look like:

Ben4594,Password,Ben

I'm Using python 3 and tkinter.

Upvotes: 1

Views: 59

Answers (1)

Prune
Prune

Reputation: 77857

You suffer from name collision. Look at this spot in your code:

U = input1.get()
P = input2.get()
R = input3.get()

def P():
#        <=============== point of interest
    myData = [[U, P, R]]

You had a simple variable P, but you just overwrote that with a function definition of the same name. Thus, when you write to your file, you get the value of the function, that being the function descriptor.

Change your variable names to avoid the collision. In general, use meaningful names, and you'll avoid this problem (and many others).

user_id      = input1.get()
password     = input2.get()
display_name = input3.get()

def write_user_to_file():
    myData = [[user_id, password, display_name]]

Also, consider using function parameters instead of global variables.

Upvotes: 1

Related Questions