Question

i wrote a code that is pretty simple, but i cant understand one thing. Code looks like that

name = open("test.txt")

def CountLines(name):
    return len(name.readlines())

def CountChars(name):
    return len(name.read())


print(CountLines(name))
print(CountChars(name))

And now let's say the "test.txt" contains 4 lines of text (line1, line2, line3, line4). After running this code i would get the output:

4
0

First one is ok, but why the second is 0? Because earlier function set to EOF? And if so, why it doesn't read the file from beginning? Is there a way to reload the file?

Was it helpful?

Solution

Yes, the second is 0 because you've already read the whole file, so there's nothing left to read in CountChars.

You need to put name.seek(0) in there to get back to the start of the file before you call CountChars. Check out the file object documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top