简体   繁体   English

将变量保存在文本文件中

[英]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. 使用dict对象将名称映射到值可以更方便地进行管理。

You may also want to read about the pickle or json modules which provide easy serialization of objects such as dict . 您可能还想阅读有关picklejson模块的信息,这些模块可以轻松地序列化对象,例如dict

The way to use a serializer such as pickle is: 使用pickle等序列化程序的方法是:

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. 您可以在提供的代码中将pickle更改为json ,以使用其他标准序列化程序并以json格式存储对象。

Edit: 编辑:

In your example you're trying to store text from tkinter 's Entry widget. 在您的示例中,您尝试存储来自tkinterEntry小部件的文本。 Read about it here . 在这里阅读它。

What you probably miss is using a StringVariable to capture the entered text: 你可能错过的是使用StringVariable来捕获输入的文本:

Create StringVar for variables: 为变量创建StringVar

username = StringVar()
password = StringVar()

Register StringVar variables to Entry widgets: 将StringVar变量注册到Entry小部件:

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

Save content using StringVar in two seperate files: 使用StringVar在两个单独的文件中保存内容:

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: 如果你想在同一个文件中创建一个映射( dict )并存储它:

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

Edit 2: 编辑2:

You were using the serialization before entering text. 输入文本之前使用了序列化。 Register a save function (that can later exit) to the register button. save功能(稍后可以退出)注册到注册按钮。 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 . 将变量存储在.txt文件中通常不是一个好习惯,Python有一个非常好的库作为Pickle However still you can analyse both methods and choose one. 但是,您仍然可以分析这两种方法并选择一种。

Method 1: 方法1:

Using a .txt file: 使用.txt文件:

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: 方法2:

Using the Pickle module: 使用Pickle模块:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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