【发布时间】:2015-09-04 13:05:58
【问题描述】:
我为我的 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()
我的输出:
1,1
,False
1,2
,False
1,3
,False
【问题讨论】:
-
你没有显示你的输出,但我敢打赌它看起来像
id, id<newline>,False,或类似的。使用%r而不是%s可以更好地诊断。 -
如果不告诉我们输入文件的内容,代码 sn-p 并不是很有用,但是 Python 不会为
"1" == "1"返回False,它会返回False进行任何比较你实际上是在两个不相等的物体之间制作。在print()调用之前,请尝试print(repr(remID), repr(sctID)),这样您就可以看到正在比较的实际项目。您使用的格式化调用将在视觉上消除类型等差异。 -
@MartijnPieters 我添加了我得到的输出
-
额外的换行符没有提示你?你认为它来自哪里?
-
@TigerhawkT3 这是一个公平的观点,我对此有点担心,但我什至不认为这可能是问题的根源。不过现在都修好了,谢谢:)
标签: python string file integer logic