Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a variable in a text file

I would like to save variable (including its values) into a text file, so that the next time my program is opened, any changes will be automatically saved into the text file .For example:

    balance = total_savings - total_expenses 

How would I go about saving the variable itself into a text file instead of only its value? This section is for the register page

    from tkinter import *
    register = Tk()
    Label(register, text ="Username").grid(row = 0)
    Label(register, text ="Password").grid(row = 1)

    e1 = Entry (register)
    e2 = Entry (register, show= "*")

    e1.grid(row = 0, column = 1)
    e2.grid(row = 1, column = 1)

    username = e1.get()
    password = e2.get()


    button1 = Button(register, text = "Register", command = register.quit)
    button1.grid(columnspan = 2)
    button1.bind("<Button-1>")

    import json as serializer
    with open('godhelpme.txt', 'w') as f:
        serializer.dump(username, f)
    with open('some_file.txt', 'w') as f:
        serializer.dump(password, f)


    register.mainloop()

Altered code:

    from tkinter import *
    register = Tk()
    Label(register, text ="Username").grid(row = 0)
    Label(register, text ="Password").grid(row = 1)

    username = StringVar()
    password = StringVar()

    e1 = Entry (register, textvariable=username)
    e2 = Entry (register, textvariable=password, show= "*")

    e1.grid(row = 0, column = 1)
    e2.grid(row = 1, column = 1)


    button1 = Button(register, text = "Register", command = register.quit)
    button1.grid(columnspan = 2)
    button1.bind("<Button-1>")

    import json as serializer
    with open('godhelpme.txt', 'w') as f:
        serializer.dump(username.get(), f)
    with open('some_file.txt', 'w') as f:
        serializer.dump(password.get(), f)

Log in code:

    from tkinter import *
    login = Tk()
    Label(login, text ="Username").grid(row = 0)
    Label(login, text ="Password").grid(row = 1)

    username = StringVar()
    password = StringVar()

    i1 = Entry(login, textvariable=username)
    i2 = Entry(login, textvariable=password, show = "*")

    i1.grid(row = 0, column = 1)
    i2.grid(row = 1, column = 1)

    def clickLogin():
            import json as serializer
            f = open('godhelpme.txt', 'r')
            file = open('some_file.txt', 'r')
            if username == serializer.load(f):
                    print ("hi")
            else:
                    print ("invalid username")
                    if password == serializer.load(file):
                            print ("HELLOOOO")
                    else:
                            print ("invalid password")



    button2 = Button(login, text = "Log In", command = clickLogin)
    button2.grid(columnspan = 2)


    login.mainloop()
like image 315
honeybadger Avatar asked May 09 '15 11:05

honeybadger


People also ask

How do I save a variable in a text file?

save with -ascii is reserved for numeric values and cannot be used to save text. If you need to save text you will need to fopen/fprintf/fclose .

How do I save a variable to a text file in Python?

We can use concatenation within the write() function to save a variable to a file in Python. Here, we will also use the str() or the repr() function to convert the variable to a string and then store it in the file. The following code uses string concatenation to save a variable to a file in Python.

How do I save a variable to a text file in MATLAB?

To write a text file with columns of data that have variable names, use the “writetable” function. First, create the data to write, put it in a table with variable names, and then write the data to text file. Starting in R2019a, you can use "writematrix" to write a matrix to a file.


1 Answers

You have to know the variable's name at compilation time. So all you need to do is:

with open('some_file.txt', 'w') as f:
    f.write("balance %d" % balance)

This can be more convenient to manage using a dict object for mapping names to values.

You may also want to read about the pickle or json modules which provide easy serialization of objects such as dict.

The way to use a serializer such as pickle is:

import pickle as serializer

balance = total_savings - total_expenses 
with open('some_file.txt', 'w') as f:
    serializer.dump( balance, f)

You can change pickle to json in the provided code to use the other standard serializer and store objects in json format.

Edit:

In your example you're trying to store text from tkinter's Entry widget. Read about it here.

What you probably miss is using a StringVariable to capture the entered text:

Create StringVar for variables:

username = StringVar()
password = StringVar()

Register StringVar variables to Entry widgets:

e1 = Entry (register, textvariable=username)
e2 = Entry (register, textvariable=password, show= "*")

Save content using StringVar in two seperate files:

import json as serializer
with open('godhelpme.txt', 'w') as f:
    serializer.dump(username.get(), f)
with open('some_file.txt', 'w') as f:
    serializer.dump(password.get(), f)

If you want them in the same file create a mapping (dict) and store it:

import json as serializer
with open('godhelpme.txt', 'w') as f:
    serializer.dump(
        {
            "username": username.get(),
            "password": password.get()
        }, f
    )

Edit 2:

You were using the serialization before entering text. Register a save function (that can later exit) to the register button. This way it will be called after the user clicked it (that means the content is already there). Here is how:

from tkinter import *

def save():
    import json as serializer
    with open('godhelpme.txt', 'w') as f:
        serializer.dump(username.get(), f)
    with open('some_file.txt', 'w') as f:
        serializer.dump(password.get(), f)
    register.quit()

register = Tk()
Label(register, text ="Username").grid(row = 0)
Label(register, text ="Password").grid(row = 1)

username = StringVar()
password = StringVar()

e1 = Entry (register, textvariable=username)
e2 = Entry (register, textvariable=password, show= "*")

e1.grid(row = 0, column = 1)
e2.grid(row = 1, column = 1)

# changed "command"
button1 = Button(register, text = "Register", command = save)
button1.grid(columnspan = 2)
button1.bind("<Button-1>")
register.mainloop()

What happened before was the save-to-file process happened immediately before the user inserts any data. By registering a function to the button click you can ensure that only when the button is pressed, the function executes.

I strongly suggest you play with your old code in a debug environment or use some prints to figure out how the code works.

like image 121
Reut Sharabani Avatar answered Sep 24 '22 05:09

Reut Sharabani