【问题标题】: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
  • 我可以使用微软访问吗?
  • 是的,这也行。

标签: python


【解决方案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

【讨论】:

  • 这是否将用户输入的值存储为多个变量?
猜你喜欢
  • 1970-01-01
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-15
  • 1970-01-01
  • 2014-06-10
相关资源
最近更新 更多