I've written a scout system for my A Level computing task. The program is designed to store information on scouts at a scout hut, including badges, have a leaderboard system, and a management system for adding/finding/deleting scouts from the list. The scout information MUST be stored in a file.
File handling process for remove function (where my issue lies): The remove scout button triggers a popup window (using tkinter). The window collects the ID of the scout, then searches through the scout file, scanning the ID of the scouts stored and comparing it to the ID that was entered. If the ID is found, it skips this line of the file, otherwise the line is copied to a temp file. Once all lines are done, the lines in temp are copied to a new blank version of the original file, and deletes/recreates the temp file as blank.
My issue: The issue is when the program compares the ID to remove (remID) with the ID of the scouts currently being looked at in the file (sctID), it returns false when in fact they are equal. It may be an issue with my handling of the variables, my splitting of the line to get the ID, or even my data types. I just don't know. I tried converting both to string, but still false. The code for this section is below. Thank you in advance!
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()
My output:
1,1
,False
1,2
,False
1,3
,False
By conversion to string, you hide the error.
Always try repr(value) instead of str(value) for debugging purposes. You should also know, that it is better to compare integers instead of strings -- e.g. " 1" != "1".
Edit: From your output, it is clear that you have an extra '\n' (Newline) in the sctID. Because you compare strings, this will be always be False.
I guess, you have either strings with additional blanks or other hidden chars or just different types of the values, what would also provoke a different result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With