Complete the code to open a file using the with statement.
with open('example.txt', [1]) as file: content = file.read()
The mode 'r' opens the file for reading inside the with block.
Complete the code to ensure the file is automatically closed after the with block.
with open('data.txt', 'r') as file: data = file.read() print(file.[1])
The file is automatically closed after the with block, so file.closed is True.
Fix the error in the with statement to correctly handle exceptions.
try: with open('log.txt', 'r') as file: content = file.read() except [1] as e: print('Error:', e)
FileNotFoundError is the specific exception when the file does not exist.
Fill both blanks to create a context manager that prints messages before and after the block.
class MessageManager: def __enter__(self): print([1]) def __exit__(self, exc_type, exc_val, exc_tb): print([2]) with MessageManager(): print('Inside block')
The __enter__ method prints 'Entering block' before the block, and __exit__ prints 'Exiting block' after.
Fill all three blanks to create a dictionary comprehension that maps file names to their sizes if size is greater than zero.
files = {'a.txt': 100, 'b.txt': 0, 'c.txt': 50}
sizes = [1]: [2] for [3] in files.items() if [2] > 0The comprehension maps each file name to its size only if size > 0. The loop unpacks name and size from files.items().