My program is suppose to be reading from a file of scores which works all fine and dandy. However, I need to check this file to see if someone has there name in it 3 or more times. My method for checking this is:
with open(fileName,"a+") as f:
i = 0
for i, l in enumerate(f, 1):
pass
count = 0
for find in range(i):
data = f.readline()
if vName in data:
count+=1
if count ==3:
print("You have already played 3 times!")
return 0
else:
continue
else:
continue
Enumerate counts the amount of lines in the file. Then I create a loop with the amount of lines and read the data line by line. Then I check if the name is in that data. A small sample of the file I check:
Reece 7
Reece 3
Reece 2
John 1
So Reece is there 3 times, why doesn't my program see that? I checked that vName is correct and it is, when I print vName I receive "Reece". So again... why doesn't my program find this in the file.
Looks like your first loop reads through the entire file, and so by the time you run your second loop the file has already ended. Could do a f.seek(0)
to start over. Alternatively, the following only goes through the file once:
#!/usr/bin/env python
def check(filename, vName):
with open(filename, 'r') as f:
count = 0
for data in f:
if vName in data:
count += 1
if count == 3:
print("You have already played 3 times!")
return 0
check("a.txt", "Reece")