我不确定以下逻辑有什么问题。任务是生成一个ID,检查它是否存在于文件(Sample.txt)中,如果已经存在,则生成一个新代码,直到创建唯一的代码为止。每当在初始阶段创建唯一ID时,它将转到else循环。如果生成了一个现有的ID,它将首先转到if循环,生成一个新的ID,然后不再进行比较,而是直接跳转到else循环,向文件中添加重复的ID。
#!/usr/bin/env python3
import random
import string
import os.path
# Take user inputs
NetID = input("Enter the NetID: ")
CompTemp = input("Enter the Compliance template: ")
Channel = input("Enter the Channel: ")
Env = input ("Enter the environment 'P' or 'T': ")
Const = "WG"
Var1 = str((random.randint(0,9)))
Var2 = random.choice(string.ascii_uppercase)
#i=0
FSID=Const+Channel+NetID+Var1+Env
print("Original FSID: ", FSID)
datafile = "C:\\Work\\Sample.txt"
f2=open(datafile)
# Define function
def CrtFSID():
""" Generate FSID"""
global FSID
Var1 = str((random.randint(0,9)))
FSID = Const+Channel+NetID+Var1+Env
print("New FSID code case 1: ", FSID)
return FSID
for line in open("C:\\Work\\Sample.txt", "r"):
if FSID in f2.read():
print("generate new FSID code")
CrtFSID()
print("Changed FSID is: ", FSID)
continue
else:
f=open(datafile, "a")
f.write("Adding new FSID %s\r\n" % FSID)
print("I am in else loop")
f.close()
break
print("Unique FSID added into the file: ", FSID)
Shell输出:
Enter the NetID: KL123
Enter the Compliance template: ABC_01
Enter the Channel: TB
Enter the environment 'P' or 'T': P
Original FSID: WGTBKL1239P
generate new FSID code
New FSID code case 1: WGTBKL1237P
Changed FSID is: WGTBKL1237P
I am in else loop
Unique FSID added into the file: WGTBKL1237P
答案 0 :(得分:0)
问题在这里。
if FSID in f2.read():
print("generate new FSID code")
CrtFSID()
print("Changed FSID is: ", FSID)
continue
假设唯一ID为12,并且存在于文件中,根据您的逻辑,我们现在处于if循环中。在这里,您正在创建新的唯一ID(CrtFSID()
)。如果创建的ID也存在于文件中怎么办?您不处理这种情况。
使用
file = f2.read()
while FSID in file:
FSID = crtFSID()
f=open(datafile, "a")
f.write("Adding new FSID %s\r\n" % FSID)
print("I am in else loop")
f.close()
答案 1 :(得分:0)
您可以生成新的fsid
并检查它是否在Sample.txt
中。如果不是,请生成新的fsid
并重复检查。如果是,请将其写入Sample.txt
并中断循环:
import random
net_id = input('Enter the NetID: ')
channel = input('Enter the Channel: ')
env = input('Enter the environment "P" or "T": ')
with open('Sample.txt', 'r') as f:
data = f.read()
while True:
fsid = 'WG{}{}{}{}'.format(channel, net_id, random.randint(0, 9), env)
if fsid not in data:
with open('Sample.txt', 'a') as f:
f.write(fsid)
break
print('Unique FSID added into the file: {}'.format(fsid))
输出:
Enter the NetID: KL123
Enter the Channel: TB
Enter the environment "P" or "T": P
Unique FSID added into the file: WGTBKL1237P