简体   繁体   中英

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()

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.

It is often not a good practise to store a variable in a .txt file, Python has a very nice library as Pickle . However still you can analyse both methods and choose one.

Method 1:

Using a .txt file:

with open("variable_file.txt", "w") as variable_file:
    variable_file.write("a = 10")

And while retrieving the value you can use:

with open("variable_file.txt", "r") as variable_file:
    for line in variable_file.readlines():
        eval(line.strip())

Method 2:

Using the Pickle module:

import pickle

a = 10

pickle.dump( a, open( "save.p", "wb" ) )

#Load the variable back from the pickle file.

a = pickle.load( open( "save.p", "rb" ) )

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