You want to read a large log file line by line and count how many lines contain the word 'error'. Which code snippet correctly does this?
hard🚀 Application Q15 of Q15
Python - File Reading and Writing Strategies
You want to read a large log file line by line and count how many lines contain the word 'error'. Which code snippet correctly does this?
Acount = 0
with open('log.txt') as f:
lines = f.readlines()
for line in lines:
if 'error' in line:
count += 1
print(count)
Bcount = 0
with open('log.txt') as f:
for line in f:
if 'error' in line:
count += 1
print(count)
Ccount = 0
f = open('log.txt')
lines = f.readlines()
for line in lines:
if 'error' in line:
count += 1
f.close()
print(count)
Dcount = 0
with open('log.txt') as f:
for line in f:
if line == 'error':
count += 1
print(count)
Step-by-Step Solution
Solution:
Step 1: Choose efficient line-by-line reading
count = 0
with open('log.txt') as f:
for line in f:
if 'error' in line:
count += 1
print(count) uses 'with open' and iterates file line by line, which is memory efficient for large files.
Step 2: Check condition for counting 'error' in line
count = 0
with open('log.txt') as f:
for line in f:
if 'error' in line:
count += 1
print(count) correctly checks if 'error' is anywhere in the line and increments count.
Final Answer:
count = 0\nwith open('log.txt') as f:\n for line in f:\n if 'error' in line:\n count += 1\nprint(count) -> Option B
Quick Check:
Efficient reading + correct condition = count = 0
with open('log.txt') as f:
for line in f:
if 'error' in line:
count += 1
print(count) [OK]
Quick Trick:Use with open and for line in file for big files [OK]
Common Mistakes:
MISTAKES
Using readlines() for big files (memory issue)
Forgetting to close file without with
Checking line equality instead of substring
Master "File Reading and Writing Strategies" in Python
9 interactive learning modes - each teaches the same concept differently