file rewind?

Eyal Lotem eyal at hyperroll.com
Sat Apr 6 10:08:04 EST 2002


joel8bit wrote:

> I have this code:
> 
> def countLines(file):
>     numLines = 0
>     for line in file.readlines():
>         print line
>         numLines = numLines + 1
> 
>     print numLines
> 
> def countChars(file):
>     numChars = 0
>     for line in file.readlines():
>         print line
>         for char in line:
>             print char
>             numChars += 1
>     print numChars
> 
> def test(name):
>     file = open(name, "r")
>     countLines(file)
>     countChars(file)
> 
> if __name__ == "__main__":
>     test("C:\\test.txt")
> 
> when I run the module from the comman line by itself, it counts the lines
> alright, but does not count the characters.  do I need to "rewind" the
> file reference after the first function call to countLines()?

Yes, you can do this with:
file.seek(0)

Also, I would suggest the alternate code:

        def countLines(file):
                return len(file.readlines())

        def countChars(file):
                return len(file.read())

Or if you want to be more efficient:

        def countChars(file):
                cur_offset = file.tell()        # remmember current position
                file.seek(0, 2)                 # seek to end of file
                file_len = file.tell()          # the end-position (number of bytes)
                file.seek(cur_offset)           # seek back to where we were
                return file_len




More information about the Python-list mailing list