0
0
Pythonprogramming~10 mins

Best practices for resource management in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to open a file safely using a context manager.

Python
with open('example.txt', [1]) as file:
    content = file.read()
Drag options to blanks, or click blank then click option'
A'r'
B'x'
C'a'
D'w'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' or 'a' mode when only reading is needed.
2fill in blank
medium

Complete the code to ensure a file is closed properly after writing.

Python
file = open('output.txt', [1])
file.write('Hello')
file.close()
Drag options to blanks, or click blank then click option'
A'w'
B'a'
C'x'
D'r'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'r' mode when trying to write to a file.
3fill in blank
hard

Fix the error in the code to properly handle file opening with a context manager.

Python
file = open('data.txt', 'r')
with [1] as f:
    data = f.read()
Drag options to blanks, or click blank then click option'
Adata
Bopen('data.txt', 'r')
Cfile
Df
Attempts:
3 left
💡 Hint
Common Mistakes
Using open() again inside the with statement causing resource leaks.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that stores file sizes for files larger than 1000 bytes.

Python
sizes = {filename: [1] for filename, size in files.items() if size [2] 1000}
Drag options to blanks, or click blank then click option'
Asize
B>
C<
Dfilename
Attempts:
3 left
💡 Hint
Common Mistakes
Using filename as value or wrong comparison operator.
5fill in blank
hard

Fill all three blanks to create a safe file reading dictionary comprehension filtering files with '.txt' extension.

Python
file_contents = [1]: open([2], 'r').read() for [3] in filenames if [2].endswith('.txt')
Drag options to blanks, or click blank then click option'
Afilename
Dfile
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causing NameError.