Essential storage keeps sign-in and learning features working. Google Analytics measures visits; Microsoft Clarity records interactions to help us improve usability. Both are optional and stay off until you choose. Read our privacy policy.
Summarize a text file safely coding exercise | SovranCode
Design summarize_file so it reads UTF-8 text, returns line and word counts, and gives the caller a useful error result for a missing or undecodable file instead of crashing.
Requirements
Use with open
Specify UTF-8
Handle FileNotFoundError and UnicodeDecodeError separately
Show a hint
Write down the input contract and the failure cases before coding.
tests
Loads Python in an isolated browser worker, then runs your function
RUNTIME OUTPUT
Ready to run the file open above.
LEARN FROM THE SOLUTION
Why the solution works.
The context manager closes the file on both success and failure. Narrow exception handling keeps missing files distinct from text-encoding problems, giving a caller a stable result it can display or retry.
What this exercise teaches
Context managers
Exception handling
Result contracts
A PRACTICAL PLAN
Work through Summarize a text file safely with intent.
Translate the contract.Turn the requirements into a short checklist before editing your-solution.py.
Use the example as evidence.Predict the result for the supplied input, then add one boundary case such as an empty value, a limit, or unexpected input.
Review the implementation.Compare your choices against solution.py only after a real attempt.
EXERCISE FAQ
Before you move on.
What does “Summarize a text file safely” teach?
This advanced Python exercise focuses on Context managers, Exception handling, Result contracts. Its requirements define the exact behavior to implement before you write code.
How should I validate this Python solution?
Open your-solution.py and select Run code. The browser loads Python in an isolated worker and runs your function against the visible tests.
When should I open the reference solution?
Attempt Summarize a text file safely first. Then open the read-only solution file to compare the contract, edge-case handling, and implementation choices—not simply to copy the final code.