import os, tempfile
os.chdir(tempfile.mkdtemp())
with open("story.txt", "w") as f:
f.write("Once upon a time\nthere was a coder.\n\nThe end.\n")
lines = words = chars = blank = 0
with open("story.txt") as f:
for line in f:
lines += 1
chars += len(line)
words += len(line.split())
blank += not line.strip()
print(f"lines={lines} words={words} chars={chars} blank={blank}")
Output Verified by running it on Python 3
lines=4 words=10 chars=46 blank=1
Iterating counts lines one at a time. A blank line strips to "", and not "" is True, which adds 1.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!