I'm trying to make a function that counts the number of lines in a txt file. I have made the file readable earlier in the program. Here is what I've done:
Allow the program to open the file:
datahandle = open("dataset.txt")
"dataset.txt" is a notepad document with 10 rows of numbers:
18
3
10
42
50
13
100
40
77
67
Here is the function I defined:
def findn():
global count
count = 0
for countingdata in datahandle:
countingdata = countingdata.rstrip()
count = count + 1
I then call this function later with:
findn()
print(count)
When I do this the first time, it returns the correct answer (10 lines). However, if I run this again it returns 0. If I keep running it afterwards it keeps returning 0.
I've tried making a variable that changes from true to false depending on if I've run the function before, and if I have I then just have it print "count" as it was.
I've also tried moving the place where I define count as 0 at the start outside of the function but this just doesn't work.
Obviously, the program should always return the number of lines in the file (10).
Think of datahandle
as a position in the file. Once you've iterated over it, it points to the end of the file, so the next time you iterating over it, the loop will no execute (or, you can think of it as iterating zero times).
To address this, you can reopen the file every time you call the function.
In addition, there's no point in making count
global. Instead, just return it from the function
def find():
with open("dataset.txt") as datahandle:
count = 0
for countingdata in datahandle:
countingdata = countingdata.rstrip() # Copied from OP, but not really needed.
count = count + 1
return count