如何将变量存储在文件中,以便它们将它们的值保存在我可以在程序中打印出来的位置? [复制]

Posted

技术标签:

【中文标题】如何将变量存储在文件中,以便它们将它们的值保存在我可以在程序中打印出来的位置? [复制]【英文标题】:How do I store variables in a file so that they keep their values where I can print them out in the program? [duplicate] 【发布时间】:2020-01-06 10:38:10 【问题描述】:

我想将值存储在文件中,以便它们保持其属性。请在下面查看我的代码的 sn-p。

        if selection == ("1"):
            newUserID = input ("Please enter their 3 digit ID: ")
            #check the user has put in numbers and at least 3 digits
            newUserName = input("Please enter the employees name: ")
            #check for string not number. Has to be exactly their name
            newUserPassword = input ("Please enter their Clocking in password: ")
            count = count + 1
            uniqueUserID = (newUserID, newUserName, newUserPassword, count)
            uniqueUserID = str(uniqueUserID)
            file.write(uniqueUserID)
            file.close()

我正在使用 Python,还需要将用户的输入存储在一个“count”变量中,以跟踪有多少用户。

谢谢。

【问题讨论】:

您可能想开始研究使用数据库 我将如何使用 python 做到这一点?抱歉 - 我对编码很陌生。 您可以使用本地 SQLite 数据库。您将能够创建一个名为 users 的表,其中包含 id、用户名和密码作为字段。作为介绍,我建议阅读这篇文章:datatofish.com/create-database-python-using-sqlite3 我可以使用微软访问吗? 是的,这也行。 【参考方案1】:

将它们的值放入如下所示的字典中,然后将字典作为 json 写入文件中。

dict = 
dict['newUserID'] = newUserID
dict['newUserName'] = newUserName
dict['newUserPassword'] = newUserPassword
dict['count'] = count
with open('data.json', 'w') as fp:
    json.dump(dict, fp)

这假设import json

【讨论】:

这是否将用户输入的值存储为多个变量?

以上是关于如何将变量存储在文件中,以便它们将它们的值保存在我可以在程序中打印出来的位置? [复制]的主要内容,如果未能解决你的问题,请参考以下文章