Write a function that counts the words in a file.
count_words_in_file(path)
Open the file at path, read its contents, and return the number of whitespace-separated words.
Given a file containing "the quick brown fox", count_words_in_file(path) returns 4.
def count_words_in_file(path):
with open(path) as f:
content = f.read()
return len(content.split())
The with block reads the entire file into content as one string, and closes the file automatically once the block ends. From there, this is exactly the string-splitting you've done before (back in Count Vowels and Reverse Words) — content.split() breaks the text into a list of words on any whitespace, and len(...) counts them.
Notice content isn't used again after the with block ends — that's fine, and typical: you read everything you need while the file is open, then work with that data after it's closed. You wouldn't want to keep the file open longer than necessary.
def count_words_in_file(path):
with open(path) as f:
content = f.read()
return len(content.split())
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.