如果我在我的python应用程序中添加这两个变量,如何将输入到'key'的输入与文本行(整数,例如:12345,67890)进行比较,以便在位于www.example的文本文件中查找匹配值。 com / key.txt?
name = raw_input("What is your name ? ")
key = raw_input("What is your key ? ")
我还考虑过将它与数据库内容进行比较,但是下面的代码不起作用。
import mysql.connector
email = raw_input("What is your email ? ")
key = raw_input("What is your key ? ")
cnx = mysql.connector.connect(user='root', password="79032", database='license_key')
cursor = cnx.cursor()
query = ("SELECT email_address, license_key FROM validation "
"WHERE license_key LIKE key")
cursor.execute(query, (license_key))
for (email_address, license_key) in cursor:
print("you license key is valid"))
cursor.close()
cnx.close()
答案 0 :(得分:1)
您需要读取文本文件(字典可以工作),然后检查密钥/以这种方式分配新值。如果需要,您可以再次将其保存为文本。
示例:如果您有一个包含两列的文本文件(第一个是键,第二个是值),您可以执行以下操作:
example_dict = {}
# Open the file (this takes a path to the file)
with open("key.txt") as f:
# Loop over each line
for line in f:
# Split each line and get the 1st (key) and 2nd (val) values
(key, val) = line.split()
# Cast the key to an integer (not necessary if your key is a string)
example_dict[int(key)] = val
然后,找一把钥匙:
name = raw_input("What is your name ? ")
key = raw_input("What is your key ? ")
# Here you check if the key is present
if key in example_dict:
# Here you set it to something new, like the name you got, if you wanted to
example_dict[key] = name