[英]Check if a generated key already exists in a file
so i am working on a script which generates random numbers and chars with uuid4. 所以我正在研究一个脚本,该脚本使用uuid4生成随机数和字符。 Those generated keys are saved in a list and this list will be saved in a file called "already_used.txt".
这些生成的密钥将保存在一个列表中,并且此列表将保存在一个名为“ already_used.txt”的文件中。 My Question is:
我的问题是:
How can i check my generated keys so that they are not in the already_used file, so i get unique keys. 我如何检查我生成的密钥,以便它们不在已经使用的文件中,所以我获得了唯一的密钥。
import uuid
checklist_idfile = open('already_used.txt', 'a')
already_used = []
def checklist(string_length=9):
count = 0
while count < 20:
count += 1
checklist_random = str(uuid.uuid4())
checklist_random = checklist_random.replace("-","")
checklist_prefix = 'TEST_'
id_checklist_random = checklist_prefix + checklist_random[0:string_length]
print id_checklist_random
already_used.append(id_checklist_random)
checklist_idfile.write(id_checklist_random)
checklist_idfile.write('\n')
a generated key looks like this: TEST_d1c23ba2f Thank you very much! 生成的密钥如下所示:TEST_d1c23ba2f非常感谢!
If I understand correctly the question, you need to do something like : 如果我对问题的理解正确,则需要执行以下操作:
with open("already_used.txt", "r") as used:
already_used = {x.rstrip() for x in used}
if not some_key in already_used:
doing somethig
...
You can check for keys in collection with in
keyword: 您可以使用
in
关键字检查集合in
键:
if key in collection: do_something()
But beware, that if collection is list
, it will take long time (for every key you check, you need to look trough almost whole list) 但是请注意,如果collection是
list
,则将花费很长时间(对于您检查的每个键,您几乎都需要查看整个列表)
If you want to check for more keys at once, make a set from the collection you want to compare against (set has constan, like so: 如果要一次检查更多键,请从要比较的集合中设置一个集合 (集合具有常量,如下所示:
my_set = set(some_collection)
for key in keys:
if key in my_set: do_something()
If you want to make set from file, do something like this: (assuming every key is at new line) 如果要从文件中进行设置,请执行以下操作:(假设每个键都位于新行)
key_set = set([x.strip() for x in open("file.txt")])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.