Kri*_*ice 3 python string logic integer file
我为我的A Level计算任务编写了一个侦察系统.该计划旨在存储侦察小屋的侦察员信息,包括徽章,排行榜系统,以及用于从列表中添加/查找/删除侦察员的管理系统.侦察信息必须存储在文件中.
删除功能的文件处理过程(我的问题所在):删除侦察按钮触发弹出窗口(使用tkinter).该窗口收集侦察员的ID,然后搜索侦察文件,扫描存储的侦察员的ID并将其与输入的ID进行比较.如果找到该ID,它将跳过该文件的这一行,否则该行将被复制到临时文件中.完成所有行后,temp中的行将复制到原始文件的新空白版本,并将临时文件删除/重新创建为空白.
我的问题:问题是当程序将要删除的ID(remID)与当前正在文件中查找的侦察程序的ID(sctID)进行比较时,它实际上在它们相等时返回false.这可能是我处理变量,分割行以获取ID,甚至我的数据类型的问题.我只是不知道.我尝试将两者都转换为字符串,但仍然是假的.本节的代码如下.先感谢您!
elif self._name == "rem":
remID = str(scoutID.get())
if remID != "":
#store all the lines that are in the file in a temp file
with open(fileName,"r") as f:
with open(tempFileName,"a") as ft:
lines = f.readlines()
for line in lines:
sctID = str(line.split(",")[3])
print("%s,%s,%s"%(remID, sctID, remID==sctID))
#print(remID)
if sctID != remID: #if the ID we are looking to remove isn't
#the ID of the scout we are currently looking at, move it to the temp file
ft.write(line)
#remove the main file, then rectrate a new one
os.remove(fileName)
file = open(fileName,"a")
file.close()
#copy all the lines back to the main file
with open(tempFileName,"r") as tf:
lines = tf.readlines()
with open(fileName,"a") as f:
for line in lines:
f.write(line)
#finally, delete and recreate the temp file
os.remove(tempFileName)
file = open(tempFileName,"a")
file.close()
#remove the window
master.destroy()
Run Code Online (Sandbox Code Playgroud)
我的输出:
1,1
,False
1,2
,False
1,3
,False
Run Code Online (Sandbox Code Playgroud)
通过转换为字符串,您可以隐藏错误.
始终尝试使用repr(value)而不是str(value)进行调试.您还应该知道,比较整数而不是字符串更好 - 例如"1"!="1".
编辑:从您的输出中可以清楚地看到,您在sctID中有一个额外的'\n'(换行符).因为你比较字符串,所以它总是为假.
我想,你有任何字符串与额外的空格或其他隐藏的字符或只是不同类型的值,什么也会引起不同的结果.