← Back to Exercises
Module 5

Solutions

Compare your solutions and learn best practices

⚠️ Try Before You View!

Make sure you've attempted the exercises before viewing these solutions. Learning happens when you struggle through problems yourself!

Solution 1: File Reader with Error Handling

Read and analyze text files with comprehensive error handling.

📝 Explanation

This solution demonstrates proper file handling with context managers and exception handling for common file operations errors.

💻 Code

def read_and_analyze(filename):
    """Read file and return analysis"""
    try:
        with open(filename, 'r') as file:
            content = file.read()
            lines = content.split('\n')
            words = content.split()
            
            return {
                'lines': len(lines),
                'words': len(words),
                'characters': len(content),
                'success': True
            }
    except FileNotFoundError:
        return {'success': False, 'error': 'File not found'}
    except PermissionError:
        return {'success': False, 'error': 'Permission denied'}
    except Exception as e:
        return {'success': False, 'error': str(e)}

# Example usage
filename = input("Enter filename: ")
results = read_and_analyze(filename)

if results['success']:
    print(f"\nFile Analysis:")
    print(f"Lines: {results['lines']}")
    print(f"Words: {results['words']}")
    print(f"Characters: {results['characters']}")
else:
    print(f"\nError: {results['error']}")

✨ Key Points

  • Use 'with' statement for automatic file closing
  • Handle specific exceptions separately
  • Provide meaningful error messages
  • Return structured data from functions
  • Always validate file operations

Ready for the project?

Apply everything you've learned in the module project!

View Project