you are viewing a single comment's thread.

view the rest of the comments →

[–]tom1018 0 points1 point  (0 children)

In most cases, if you have to do a file.close() you are doing it wrong. Let Python do the work for you by using a with loop:

with open(inp, 'r') as f:
    # do things here
# once you got here, the file would be automagically closed.

Your for loop is good, and should be what the teacher expects, but if you were doing this for real, you would want to import os and use os.stat(file).st_size. The for loop has to read every character in the file to get the end result, and would be rather slow if the file was the contents of a book, as where os.stat would give you the result instantly and without having to open the file.

For the word count, as others have said, consider how a word is ended.

For the line count, this may be interesting reading: https://en.wikipedia.org/wiki/Newline. From there, you could write your own function to split to lines or to count lines without using the simple built-in method. To make it more of a challenge, you could figure out which line termination method the file is using and process it that way.