0
0
Pythonprogramming~10 mins

Handling multiple resources 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 named 'data.txt' for reading.

Python
with open([1], 'r') as file:
    content = file.read()
Drag options to blanks, or click blank then click option'
A'data.txt'
B'write.txt'
C'image.png'
D'output.log'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong file name.
Forgetting to put quotes around the file name.
2fill in blank
medium

Complete the code to open two files 'input.txt' and 'output.txt' safely using a single with statement.

Python
with open('input.txt', 'r') as infile, [1] as outfile:
    data = infile.read()
    outfile.write(data)
Drag options to blanks, or click blank then click option'
Aopen('output.txt', 'r')
Bopen('output.txt', 'a')
Copen('input.txt', 'w')
Dopen('output.txt', 'w')
Attempts:
3 left
💡 Hint
Common Mistakes
Opening the output file in read mode instead of write mode.
Using the wrong file name.
3fill in blank
hard

Fix the error in the code to correctly open and read from two files using nested with statements.

Python
with open('file1.txt', 'r') as f1:
    with [1] as f2:
        data1 = f1.read()
        data2 = f2.read()
Drag options to blanks, or click blank then click option'
Aopen('file2.txt', 'r')
Bopen('file1.txt', 'w')
Copen('file1.txt', 'r')
Dopen('file2.txt', 'w')
Attempts:
3 left
💡 Hint
Common Mistakes
Opening the second file in write mode.
Using the wrong file name for the second file.
4fill in blank
hard

Fill both blanks to create a dictionary with word lengths only for words longer than 4 characters.

Python
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if len(word) [2] 4 }
Drag options to blanks, or click blank then click option'
Alen(word)
B>
C<
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself instead of its length.
Using '<' instead of '>' in the condition.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase keys and values only for items with positive values.

Python
data = {'a': 1, 'b': -2, 'c': 3}
result = { [1]: [2] for k, v in data.items() if v [3] 0 }
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
C>
Dk
Attempts:
3 left
💡 Hint
Common Mistakes
Using original keys instead of uppercase.
Using '<' instead of '>' in the condition.
Using k instead of v for values.